I think i have a function that will do it for you.
The usual WP way to highlight the menu item is to add the class “current-menu-item” to the item, then you can style highlighted links with CSS.
In this case you want to highlight a taxonomy menu link if we’re in a post for that taxonomy, is that right? For example if we’re in a post in “CategoryX” we want the menu link for “CategoryX” to be highlighted.
The following filter for Walker_Nav_Menu should help. This can go in functions.php
function my_special_nav_class( $classes, $item ) {
if( 'category' == $item->object ){
$current_category = array();
$category = get_category( $item->object_id );
$category = $category->term_id;
global $wp_query, $wp_rewrite;
$queried_object = $wp_query->get_queried_object();
$current_category[] = $queried_object->term_id;
// uncomment the following if you want to debug:
// echo '<pre>Category of this menu item<br />';
// print_r($category);
// echo '</pre>';
// echo '<pre>Category queried for this page<br />';
// print_r($current_category);
// echo '</pre>';
if( in_array( $category, $current_category ) ) {
$classes[] = 'current-menu-item';
}
}
return $classes;
}
add_filter( 'nav_menu_css_class', 'my_special_nav_class', 10, 2 );
This function filters nav_menu_css_class
which is used by Walker_Nav_Menu
.
https://core.trac.wordpress.org/browser/tags/4.1/src/wp-includes/nav-menu-template.php#L427
The filter above works for the default taxonomy “category”, but we would probably have to loop through all current post taxonomies to catch a custom taxonomy. If you only need one taxonomy, it’s simpler. I’m still working out a solution for custom taxonomies…