Skip to content

WordPress – Use add_submenu_page() content as default for admin parent page

When you use

add_menu_page();

The 5th argument is a callback for a page. If you set it, it will automatically generate a page using the second argument (Menu Title).

If you want something like this.

- Shop
-- Dashboard (default when Shop is clicked)
-- Categories

The trick is to not set the callback when adding the parent page. The 5th argument that accepts the callback function is empty.

function _my_shop_menu() {
        add_menu_page( 'Shop', 'Shop', 'manage_options', 'my-shop.php', '', plugins_url( 'myplugin/images/icon.png' ), 25);
}
 
add_action('admin_menu', '_my_shop_menu');

Then create the sub menu but map it to the parent item slug (4th argument).

    add_submenu_page( 'my-shop.php', 'Dashboard', 'Dashboard', 'manage_options', 'my-shop.php', '_my_dashboard_page');

Here is the complete demonstration. When clicking on the parent link it automatically guides the admin to the Dashboard link. We add a second sub page to better show what’s going on since WordPress will not add the Dashboard page unless there is more than 1 sub page.

function _my_shop_menu() {
 
    /*
     * Add Parent Page
     */
    add_menu_page( 'Shop', 'Shop', 'manage_options', 'my-shop.php', '', plugins_url( 'myplugin/images/icon.png' ), 10);
 
    /*
     * Add sub pages
     *
     * Require a second sub page for demonstration
     */
    add_submenu_page( 'my-shop.php', 'Dashboard', 'Dashboard', 'manage_options', 'my-shop.php', '_my_dashboard_page');
    add_submenu_page( 'my-shop.php', 'Categories', 'Categories', 'manage_options', 'my-shop-categories.php', '_my_categories_page');
}
 
add_action('admin_menu', '_my_shop_menu');
 
 
function _my_dashboard_page() {
    echo 'Dashboard';
}
 
function _my_categories_page() {
    echo 'Categories';
}

With thanks to http://wordpress.stackexchange.com/questions/66498/add-menu-page-with-different-name-for-first-submenu-item

About 

10 years + experience in web development working with lots of different technology.

Published inPHPWordPress

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *