I want to check whether a certain top-level menu is already present or not in the Wordpress admin interface:
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?
You can access the the menu editor by going to Settings -> Menu Editor. The plugin will automatically load your current menu configuration the first time you run it. If you have WordPress set up in Multisite (“Network”) mode, you can also install Admin Menu Editor as a global plugin.
The WordPress admin dashboard, often called WP Admin or WP admin panel, is essentially the control panel for your entire WordPress website. It's where you create and manage content, add functionality in the form of plugins, change styling in the form of themes, and lots, lots more.
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
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:
$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' );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With