Custom Post type menu highlighted in the archive/post

I created a custom nav menu for my custom post type by custom links (linked to the archive page). Let say I have a custom post type named “product”, and when I click on the menu, it will go to the archive page of ‘product’, and the ‘product’ will be highlighted. It is pretty easy since WP will automatically add the ‘current-menu-item’ class to the menu when in the ‘product’ archive page.

But there is a problem, in the archive page, the ‘current-menu-item’ seem only add to the 1st page of the archive. When I go to page 2 the ‘current-menu-item’ is not added in the class, and the menu not highlighted.

Read More

Apart of that, I also want the menu get highlighted when viewing the post under ‘product’ type.

So I tried to add this code to the function:

function add_active_classes($classes = array(), $menu_item = false){
global $wp_query;

if(in_array('current-menu-item', $menu_item->classes)){
    $classes[] = 'current-menu-item';
}

if ( $menu_item->post_type == 'product' && is_post_type_archive('product') ) {
    $classes[] = 'current-menu-item';
}

if ( $menu_item->post_type== 'product' && is_singular('product') ) {
    $classes[] = 'current-menu-item';
}


return $classes;
}
add_filter( 'nav_menu_css_class', 'add_active_classes', 10, 2 );

The result is nothing changed. What did I done wrong?

Related posts

Leave a Reply

1 comment

  1. You have it almost right. Try the following:

    function add_active_classes($classes = array(), $menu_item = false){
    global $wp_query;
    
    if(in_array('current-menu-item', $menu_item->classes)){
        $classes[] = 'current-menu-item';
    }
    
    if ( $menu_item->title == 'product' && is_post_type_archive('product') ) {
        $classes[] = 'current-menu-item';
    }
    
    if ( $menu_item->title== 'product' && is_singular('product') ) {
        $classes[] = 'current-menu-item';
    }
    
    
    return $classes;
    }
    add_filter( 'nav_menu_css_class', 'add_active_classes', 10, 2 );
    

    I assume that your custom post type is called “product” and that you have a page with that slug created and added to your menu