I was in need of a solution to highlight the top menu item for a custom post type when viewing a single subpage (cpt). There is no built-in method in WordPress that adds a class to the top menu item of cpt, when viewing a child item.
I spent some time searching for this topic on the net and came across this post on WordPress Answers. I specifically noticed somatics answer.
I had created a cpt called “trips”. Because it was for a danish website I could not have a menu item named Trips.
I just didn’t like having to enter the slug into my Title Attribute, as trips makes no sense in danish and I didn’t want the browser tooltip to appear on the menu line on mouseover. So I came up with idea of adding a class name of the cpt slug instead to the menu item either.
So I went into the Menus section and added this “trips-menu-item” to the css classes in the menu item.
The code below then finds the menu item with this class trips-menu-item and adds another “current_page_parent” class to it. Furthermore, it removes the “current_page_parent” from the blog menu item, if this is present.
add_filter('nav_menu_css_class', 'current_type_nav_class', 10, 2); function current_type_nav_class($classes, $item) { // Get post_type for this post $post_type = get_query_var('post_type'); // Removes current_page_parent class from blog menu item if ( get_post_type() == $post_type ) $classes = array_filter($classes, "get_current_value" ); // Go to Menus and add a menu class named: {custom-post-type}-menu-item // This adds a current_page_parent class to the parent menu item if( in_array( $post_type.'-menu-item', $classes ) ) array_push($classes, 'current_page_parent'); return $classes; } function get_current_value( $element ) { return ( $element != "current_page_parent" ); }