Reputation: 461
I have a custom post type and a custom taxonomy. Each custom post type is assigned to exactly one term. I added a menu entry for each term in my custom taxonomy. Behind each of menu entries is a overview page with all the custom posts assigned to this term. If you click on one of the customs posts a details page opens. But if you are on a details page the corresponding menu entry for the taxonomy term is no longer marked as active. What am I doing wrong?
Upvotes: 1
Views: 5334
Reputation: 1
I've been struggling with this for some time. This is how I solved my problem.
<style> .menu li.active { background-color:#000; } </style>
You can use other methods to inject the css into the archive page of course.
Upvotes: 0
Reputation: 461
Ok, I found the following solution for my problem:
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
function special_nav_class($classes, $item) {
global $naventries;
$naventries[$item->ID] = $item;
if($item->type == 'taxonomy') {
global $post;
$terms = get_the_terms($post->ID, $item->object);
$currentTerms = array();
if ( $terms && ! is_wp_error( $terms ) ) {
foreach($terms as $term) {
$currentTerms[] = $term->slug;
}
}
if(is_array($currentTerms) && count($currentTerms) > 0) {
$currentTerm = get_term($item->object_id, $item->object);
if(in_array($currentTerm->slug, $currentTerms)) {
$classes[] = 'current-menu-item';
}
}
}
return $classes;
}
But there is still one problem left. I also want to add the class current-menu-ancestor to the parent element. I have the id of the parent element via $item->menu_item_parent
but no idea how I can use this id to change the classes of the corresponding menu entry at this point?
Upvotes: 3
Reputation: 2820
You can do it via jquery:
<script type="text/javascript">
$(document).ready(function(){
var title = $(document).attr('title');
$(".maincat-list li a:contains('"+title+"')").css("text-decoration", "underline");
});
</script>
Upvotes: 0
Reputation: 11
<script type="text/javascript">
// Active state if you have a pagetitle on the result page
var currentTitle = $('.header h2').html();
$('.nav ul.menu li').find(':contains('+currentTitle+')').parent().addClass('current-menu-item');
</script>
So my solution works if you have a page title with the same name as the menu item
you would like to add the class current-page-item
to.
Ofcourse, you need jQuery installed to get this working.
edit: Make sure you put this underneath the loop on your archive-taxonomy page.
Upvotes: 1