wp_nav_menu() mark current item ancestor of custom post type

This solution does almost what I want it to.

Only thing is, I have my menu set up as follows:

Menu item 1
Menu item 2
   Custom post type 1
   Custom post type 2
   Custom post type 3
Menu item 3

Using the solution I mention adds the tag “current_url” to the sub menu of the custom post type I’m in (“Custom post type 1”). But I want it to add a “current_menu_item” (or something) to “Menu item 2”.

Any way to do this?

2 Answers
2

I do the following, it can be lengthy if you have many post types, feel free to edit it however:

/** Edit Nav Menu calsses **/
function custom_wp_nav_classes($classes, $item){
    global $post;
    $page_blog = get_option('page_for_posts');

    if(is_tax('my_taxonomy_name_here') || is_singular('my_post_type_name_here')){

        /** Remove Active Class from Blog **/
        if($item->object_id == $page_blog)
            $classes = array_filter($classes, "remove_parent");

        /** Page ID of what you want to be active **/
        if($item->object_id == 12)
            $classes[] = 'current_page_parent';
    }

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

// Remove Active Class from Blog when viewing CPTs
function remove_parent($var){
    if ($var == 'current_page_parent' || $var == 'current-menu-item' || $var == 'current-page-ancestor') { return false; }
    return true;
}

Leave a Comment