Orlando P.
Orlando P.

Reputation: 631

Wordpress add custom taxonomy to custom menu

I have searched and searched and can't find another way other than what I will refer to as the 'hack method' to add a custom taxonomy to a custom admin menu.

add_menu_page(
        'Practice Directory',
        'Practice Directory',
        'read',
        'practice-directory',
        '',
        'dashicons-welcome-widgets-menus',
        40
);

Then I register my post types and make sure they use

'show_in_menu'          => 'practice-directory',

This works and the custom post types show in my custom menu.

But a custom taxonomy doesn't accept a string for the same property only true or false.

    'show_in_menu'          => 'false',

So to add it you have to create a submenu page

add_submenu_page(
    'practice-directory',
    'Doctors',
    'Doctors',
    'edit_posts',
    'edit-tags.php?taxonomy=doctor',
    false
);

Which is a 'hacked' way of doing it.

Is there another way? Without modifying the WordPress core could I overwrite register_taxonomy function to be able to accept a string for 'show_in_menu' and follow the functionality of the register_post_type?

requested screenshot

enter image description here

Upvotes: 4

Views: 2319

Answers (1)

Butch
Butch

Reputation: 76

The only way I found is to create a submenu like you did, and set the menu active when we are on taxonomy page:

Create your admin menu:

add_menu_page('Page title', 'Menu title', 'read', 'menu_slug', false, 'dashicons-welcome-widgets-menus', 25);

Add custom post type if needed:

register_post_type('your_cpt_name', array(
    ...
    'show_in_menu' =>  'menu_slug',//your previously created menu slug
    ...
));

Add your custom taxonomy:

register_taxonomy('your_taxonomy_name', 'your_cpt_name', $args);

Add your taxonomy submenu:

add_submenu_page('menu_slug', 'Page Title', 'Menu Title', 'custom_post_capability', 'edit-tags.php?taxonomy=your_taxonomy_name&post_type=your_cpt_name', false);

Add filter for menu highlighting when active:

add_filter('parent_file', 'highlightTaxoSubMenu');

function highlightTaxoSubMenu($parent_file){
    global $submenu_file, $current_screen, $pagenow;
    if ($current_screen->post_type === 'your_cpt_name') {
        if ( $pagenow === 'edit-tags.php' && $current_screen->taxonomy === 'your_taxonomy_name' ) {
            $submenu_file = 'edit-tags.php?taxonomy=your_taxonomy_name&post_type=your_cpt_name';
        }
        $parent_file = 'menu_slug';//your parent menu slug
    }
    return $parent_file;
}

Edit: When your CPT is placed as submenu in administration, custom user Roles can't create new post for this CPT if they don't have 'edit_posts' capability ( even if they have your cpt edit capability ). A workaround is to add a 'create new post' link for this custom post in your submenu

add_submenu_page('menu_slug', 'Add', 'Add', 'custom_post_capability', 'post-new.php?post_type=your_cpt_name', false);

Upvotes: 2

Related Questions