Wordpress add submenus to custom menu

Viewed 13682

In a wordpress plugin I'm creating, it's creating a new top-level admin menu with a sub-menu page. Here's my code:

add_menu_page('Eastview Custom', 'Eastview Custom', 5,"eastview-custom");
add_submenu_page("eastview-custom","GLS Lunch Orders","GLS Lunch",5,'glsLunch','glsLunch');

So this code creates a new admin menu, "Eastview Custom". Then it adds two sublinks: "Eastview Custom" and "GLS Lunch". The problem is that I don't want "Eastview Custom" as a sublink. I would like the only sublink to be "GLS Lunch". I can't figure out how to do this. Thanks for any help!

3 Answers

You can use this function

function custom_add_admin_menu_page($args = []) {
    $args = wp_parse_args($args, [
        'page_title' => '',
        'menu_title' => '',
        'capability' => 'manage_options',
        'function'   => false',
        'menu_slug'  => '',
        'icon_url'   => '',
        'position'   => 20,
    ]);
   add_menu_page(
        $args['page_title'],
        $args['menu_title'],
        $args['capability'],
        $args['menu_slug'],
        $args['function'],
        $args['icon_url'],
        $args['position']
    );

    add_action('admin_head', function () use ($args) {
        if (!$args['function']) {
            
            remove_submenu_page($args['menu_slug'], $args['menu_slug']);
        }
    }, 99);

}

and use like below

custom_add_admin_menu_page([
    'page_title' => __('your page title', 'your domain'),
    'menu_title' => __('your menu title', 'your domain'),
    'menu_slug'  => 'your slug',
    'icon_url'   => 'dashicons-page',
    'position'   => 20,
]);
Related