Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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?

like image 978
sun Avatar asked Apr 11 '13 09:04

sun


People also ask

Where is the Admin menu in WordPress?

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.

What is WordPress Admin menu?

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.


2 Answers

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
like image 157
Joe Walker Avatar answered Sep 22 '22 17:09

Joe Walker


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' );
}
like image 22
Philipp Avatar answered Sep 24 '22 17:09

Philipp