0

I'm using the built-in menu functionality wp_nav_menu in my project: joshrodg.com/polio/, all of the posts (http://joshrodg.com/polio/star-wars/, http://joshrodg.com/polio/hello-world/, etc.) don't belong to any of the items in the navigation bar (they are not listed in the navigation bar), therefore none of the links in the navigation bar get highlighted when the posts are being shown. I was wondering if there was a way to choose a default item (Home) that could be highlighted in the event that a particular post or page doesn't have their own navigation item...that way something in the navigation bar is always highlighted.

Thanks,
Josh

1

Assuming you are loading a single piece of content like one Post (unlike the homepage where you're combining multiple Pages with JS), something like this should do it:

<script type="text/javascript">
    $(document).ready(function(){
        // get each menu item
        var hasHighlight = 0;
        // loop through to see if any have "current_page_item" class
        $("#nav ul li").each(function(obj) {
            if($(this).hasClass("current_page_item")) { hasHighlight++; }
        });
        // if none of the items are highlighted using "current_page_item" class
        if(hasHighlight == 0) {
            $("#nav ul li:first-child").addClass("current_page_item");
        }
    })(jQuery);
</script>

Enqueue this sitewide so that anytime there is a menu with id "nav" it will check and add a highlight to "Home" if nothing is highlighted.

  • This is a great solution! thank you for your help!! – Josh Rodgers Jun 5 '17 at 19:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.