Search code examples
wordpressmenuhighlighttaxonomytaxonomy-terms

wordpress nav menu does not recognize single-post as child of a term


I have a problem and I'm pulling my hair out over it.

I have a vertical nav menu which lists a taxonomy's terms and child terms.

The child terms all own a set of posts.

Upon visiting a single-post page, the menu defaults to top level and doesn't recognize that the single post is a child of any menu item. (i.e. belongs to a tax term in the menu)

Does anyone know how to have a wordpress nav menu recognize when the single post currently being displayed is a child of a term in the menu?

These pics should clarify:

Here I'm viewing gallery of items for term "filigree" child-term "rings" Viewing gallery of items for term filigree child-term rings

After Clicking on a single ring, the menu retracts to default and no highlight to show current state Click on a single ring and menu retracts to default and no highlight

Note that "our products" is always bold and not part of the menu. (don't get me started on that)


Solution

  • I found a work around to solve this, thought I'd post it in case it's useful to anobody else out there. Here is my code:

     <?php 
        $terms = wp_get_object_terms($post->ID, 'products');
    
    
        if( is_single() ){  ?>
            <script type="text/javascript">
                jQuery(function(){
                    jQuery('.menu').find(":contains('<?php echo $terms[1]->name; ?>')").show().addClass('current-menu-item');
                });         
            </script>
            <?php 
        }
    
    ?>
    
        </body>
    

    Note that 'products' is a taxonomy name and the jQuery selector simply parses my <ul> of menu items, finds a child element containing the target term and adds the class which wordpress uses to mark the current menu item 'current-menu-item'