how to check is top level admin menu exists or not in wordpress

I want to check whether a certain top-level menu is already present or not in the WordPress admin interface:

  • If it is present then I want to create a submenu in it.
  • Otherwise I want to create the top-level menu and then a submenu.

I have a few small plugins that I want organized in a single top-level menu, and then a submenu for each plugin. But how can I check for the existence of the top-level menu?

Related posts

Leave a Reply

2 comments

  1. You can do this using the global variable $menu this will return an array or items, these items has a particular index in which the name of the menu is being stored you can loop through the array to find the needed index and if is found then you just add the submenu page otherwise you can create it.

    global $menu;
    $menuExist = false;
    foreach($menu as $item) {
        if(strtolower($item[0]) == strtolower('My Menu Name')) {
            $menuExist = true;
        }
    }
    if(!$menuExist)
        // Create my menu item
    
  2. Another option is, to use the function menu_page_url():

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

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

    Usage

    The function takes two arguments:

    1. A string containing the top-menu slug
    2. Boolean flag $echo, which defaults to true.

    The second parameter is the important part: Set it to false to get a return value. If you don’t do this, then the function will echo the URL instead of returning it.

    Sample code:

    <?php
    $menu_url = menu_page_url( 'some-plugin', false );
    
    if ( $menu_url ) {
        // The top menu exists, so add a sub-menu item.
        add_submenu_page( 'some-plugin', 'Sample Page', 'My Menu', 'read' );
    } else {
        // No top menu with that slug, we can create it.
        add_menu_page( 'Sample Page', 'My Menu', 'read', 'some-plugin' );
    }