add_menu_page with no link

I wanted to create an admin menu in WordPress that does not go to a page when you click it. The Menu would be as follows.

Members <-- Top Level
View Members
Add Members

“Members”, the top level menu, would not link to anywhere. It just holds the other menu items.

The reason WHY, is that different users will have different capabilities. Some will be able to add members, but not view them, and vice-versa.

Thanks for any help! I’ve been beating my head against the wall.

2 Answers
2

You can use add_menu_page() to add the link yourself. Simply use # as menu slug. You can then use add_submenu_page() to add the other menu items yourself.

Another option would be to to fiddle with the global $menu array. Take this answer as base.

Edit: As per the comments, there needs to a top & sub menu entry

The following demo (mu-)plugin shows how you can add and remove and therefore custom rebuild your menu entries. The “magic” is using the global submenu, which gets looped through inside _wp_menu_output() in ~/wp-admin/menu-header.php. The filter that runs right before this function is the parent_file filter. Use it to intercept and alter the global. Doing so, you can safely remove the first menu entry by using remove_submenu_page(), while still having the default core behavior of a submenu items being visible when the main menu item is clicked.

(Note: A custom menu_icon can be set during post type registration.)

<?php
/** Plugin Name: (#170620) Menu Pages tests */

// Rebuild the Menu
add_action( 'admin_menu', function()
{
    $slug = 'edit.php?post_type=members';
    remove_submenu_page( $slug, $slug );
} );

// Set the Main menu items anchor back to the list page
add_filter( 'parent_file', function( $parent_file )
{
    $slug = 'edit.php?post_type=members';
    $GLOBALS['submenu'][ $slug ][10][2] = $slug;

    return $parent_file;
} );

// Register the "members" post type
add_action( 'wp_loaded', function()
{
    register_post_type( 'members', [
        'public'    => true,
        'menu_icon' => 'dashicons-universal-access',
        'labels'    => [
            'name'               => 'Members',
            'singular_name'      => 'Member',
            'add_new'            => 'Add New',
            'add_new_item'       => 'Add New Member',
            'edit_item'          => 'Edit Member',
            'new_item'           => 'New Member',
            'view_item'          => 'View Member',
            'search_items'       => 'Search Members',
            'not_found'          => 'No members found.',
            'not_found_in_trash' => 'No members found in Trash.',
            'parent_item_colon'  => null,
            'all_items'          => 'All Members',
        ],
    ] );
} );

Leave a Comment