Check if add_menu_page exists or not

The question:

I’m working on a plugin that I have to release in parts.

The problem is, if there is a menu in the page then add the new plugin to the 2nd or next submenu else add a new menu and then add the plugin to 1st submenu.

My questions:

  1. How to check that there exists a menu?
  2. If I’m coding a reusable function , that will go with every plugin then that causes conflict option.
  3. I don’t know the order of the plugin release.
add_menu_page(
    'Page Title',
    'Top Menu Title',
    'manage_options',
    'my_unique_slug',
    'my_magic_function'
);
add_submenu_page(
    'my_unique_slug',
    'page title',
    'submenu title',
    'manage_options',
    'my_submenu_slug',
    'my_magic_function_of_submenu'
);

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

You can use the fourth parameter of add_menu_page(), the my_unique_slug, to check if the page exists:

if ( empty ( $GLOBALS['admin_page_hooks']['my_unique_slug'] ) )
    add_menu_page(
        'Page Title',
        'Top Menu Title',
        'manage_options',
        'my_unique_slug',
        'my_magic_function'
    );

$GLOBALS['admin_page_hooks'] is the list of registered pages.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment