menu_page_url( string $menu_slug, bool $display = true ): string

Gets the URL to access a particular menu page based on the slug it was registered with.

Description

If the slug hasn’t been registered properly, no URL will be returned.

Parameters

$menu_slugstringrequired
The slug name to refer to this menu by (should be unique for this menu).
$displaybooloptional
Whether or not to display the URL.

Default:true

Return

string The menu page URL.

Source

function menu_page_url( $menu_slug, $display = true ) {
	global $_parent_pages;

	if ( isset( $_parent_pages[ $menu_slug ] ) ) {
		$parent_slug = $_parent_pages[ $menu_slug ];

		if ( $parent_slug && ! isset( $_parent_pages[ $parent_slug ] ) ) {
			$url = admin_url( add_query_arg( 'page', $menu_slug, $parent_slug ) );
		} else {
			$url = admin_url( 'admin.php?page=' . $menu_slug );
		}
	} else {
		$url = '';
	}

	$url = esc_url( $url );

	if ( $display ) {
		echo $url;
	}

	return $url;
}

Changelog

VersionDescription
3.0.0Introduced.

User Contributed Notes

  1. Skip to note 2 content

    We can use this function to add a sub-menu under the existing parent menu.

    // check if parent admin page exist or not.
    $main_menu = menu_page_url('PARENT-PAGE-SLUG', false);
    
    if ($main_menu) {
        // The top menu exists, so add a sub-menu item.
        add_submenu_page(
            'PARENT-PAGE-SLUG',
            esc_html__( 'Sub-Menu Page Title', 'myplugin' ), // page Title
            esc_html__( 'Sub-Menu Page', 'myplugin' ), // menu link text
            'manage_options', // capability to access the page
            'submenu-page-slug', // page URL slug
            'submenu_page_content_callback', // callback function with content
            2 // priority
        );
    } else {
        // No top menu with that slug, we can create it.
        add_menu_page(
            esc_html__( 'Parent Page Title', 'myplugin' ), // page Title
            esc_html__( 'Parent Page', 'myplugin' ), // menu link text
            'manage_options', // capability to access the page
            'parent-page-slug', // page URL slug
            'parent_menu_page_content_callback', // callback function with content
        );
    }  

You must log in before being able to contribute a note or feedback.