add_submenu_page doesn’t display submenu if menu slug is the same as in top menu

I’m trying to create a top menu and a submenu, but to prevent duplicating top menu in the submenu, I’m setting the submenu menu_slug the same as in the top menu. Why the submenu is not displayed at all in this case?

add_action("admin_menu", "setup_theme_admin_menus");    

function setup_theme_admin_menus() {    
    add_menu_page('Theme settings', 'Example theme', 'manage_options',   
        'tut_theme_settings', 'theme_settings_page');  

    add_submenu_page('tut_theme_settings',   
        'Front Page Elements', 'Front Page', 'manage_options',   
        'tut_theme_settings', 'theme_front_page_settings');   
}      

// Handler to top level menu
function theme_settings_page() {  
}  

function theme_front_page_settings() {
    echo "Some text of submenu page";  
}  

Related posts

Leave a Reply

1 comment

  1. That’s the default behavior, see the $menu_slug documentation for add_submenu_page:

    If you want to NOT duplicate the parent menu item, you need to set the name of the $menu_slug exactly the same as the parent slug.

    The problem is that putting the same slug merges the callback for the menu and the submenu.


    You may need to manipulate the global $submenu variable to achieve your goal, note that I gave a different slug to the submenu:

    add_action( 'admin_menu', 'setup_theme_admin_menus' );    
    
    function setup_theme_admin_menus() 
    {    
        add_menu_page(
            'Theme settings', 
            'Example theme', 
            'manage_options',   
            'tut_theme_settings', 
            'theme_settings_page'
        );  
    
        add_submenu_page(
            'tut_theme_settings',       // parent slug
            'Front Page Elements 2',    // page title
            'Front Page 2',             // menu title
            'manage_options',           // capability
            'tut_theme_settings2',      // slug
            'theme_front_page_settings' // callback
        );  
    
        // REMOVE THE SUBMENU CREATED BY add_menu_page
        global $submenu;
        unset( $submenu['tut_theme_settings'][0] );
    }