8
votes

I created a custom post type called “team" and added the link to the archive page to the WP menu. Once user clicks on it, he is shown all team members and that current page is highlighted in the menu. But when i click on individual team member, his page opens and the “Team” in the menu isn’t highlighted anymore, and it should be.

This is how it shows up when the team page is opened:

<li id="menu-item-17" class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item active”>
<a href="http://localhost:8888/site/team/">Team</a>
</li>

and this is what i get in the menu when i open individual member page:

<li id="menu-item-17" class="menu-item menu-item-type-custom menu-item-object-custom”>
<a href="http://localhost:8888/site/team/">Team</a>
</li>

Since I’m not a PHP developer, i don’t have any idea on how to make it work, any suggestion would be highly appreciated :)

3

3 Answers

10
votes

I got this to work for me, taken and edited from, here. Where I have 'bonsai' change it to your custom post type. Where I have put 'menu-item-299', change it to the id of your menu item that you want to keep highlighted.

function change_page_menu_classes($menu)
{
    global $post;
    if (get_post_type($post) == 'bonsai')
    {
        $menu = str_replace( 'current-menu-item', '', $menu ); // remove all current_page_parent classes
        $menu = str_replace( 'menu-item-299', 'menu-item-299 current-menu-item', $menu ); // add the current_page_parent class to the page you want
    }
    return $menu;
}
add_filter( 'nav_menu_css_class', 'change_page_menu_classes', 10,2 );

Let me know if you have issues, cos maybe they affect me to :)

1
votes

It can be done with a very simple filter in functions.php make sure that you have used the argument has_archive => true when registering CPT or using register_post_type()

//ADDING AN ACTIVE CLASS TO THE CUSTOM POST-TYPE MENU ITEM WHEN VISITING ITS SINGLE POST PAGES
function custom_active_item_classes($classes = array(), $menu_item = false){            
        global $post;

        $classes[] = ($menu_item->url == get_post_type_archive_link($post->post_type)) ? 'current-menu-item active' : '';
        return $classes;
    }
add_filter( 'nav_menu_css_class', 'custom_active_item_classes', 10, 2 );

Hope this will help someone, comment and vote up if it helps you.

0
votes

More simple way without get_post_type_archive_link function:

function custom_active_item_classes( $classes = [], $menu_item = false ) {
    global $post;

    $classes[] = ( in_array( 'menu-item-object-' . $post->post_type, $classes ) ) ? 'current-menu-item active' : '';

    return $classes;
}

add_filter( 'nav_menu_css_class', 'custom_active_item_classes', 10, 2 );