Search code examples
wordpresstaxonomy

Active menu entry for custom taxonomy - Wordpress


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?


Solution

  • 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?