questions

Highlight the current menu item?

Rate this post

So basically I’m trying to give a class “current” to highlight the menu item for the current page. I’ve tried a couple of snippets I’ve seen on this website but most of them didn’t work. This code is almost working for me, but the problem is although the current menu item is properly highlighted, Home button is also highlighted no matter which page I’m viewing. So like if I’m viewing “Archive” page, both Archive and Home are highlighted.

I’m using WordPress to build the website by the way and I’m aware that WordPress supports this effect but I’d like to achieve this without it.

HTML

<ul class="navigation">
 <li><a href="<?php echo home_url() ?>" class="navItem">Home</a></li>
 <li><a href="<?php echo home_url(/archive) ?>" class="navItem">Archive</a></li>
 <li><a href="<?php echo home_url(/about) ?>" class="navItem">About</a></li>
</ul>

JS

jQuery(function($) {
        $('.navigation li a').each(function() {
            var target = $(this).attr('href');
            if(location.href.match(target)) {
            $(this).addClass('current');
            } else {
            $(this).removeClass('current');
            }
    });
});

I’m not really familiar with javascript so there might be some errors.

Thank you for reading this, and have a great new year.

 

✔️Solution:

The suggestion of wp_nav_menu is the correct way in WordPress, but if you’re just looking for a quick solution and the menu won’t change that often, you can get by with a check inside of each list item.

<ul class="navigation">
 <li><a href="<?php echo home_url() ?>" class="navItem <?php if( is_front_page() ): echo 'current'; endif; ?>">Home</a></li>
 <li><a href="<?php echo home_url(/archive) ?>" class="navItem <?php if( is_home() || is_archive() || is_single() ): echo 'current'; endif; ?>">Archive</a></li>
 <li><a href="<?php echo home_url(/about) ?>" class="navItem <?php if( is_page('About') ): echo 'current'; endif; ?>">About</a></li>
</ul>

This makes use of WordPress’ “Conditional Tags” which effectively come back as “true” or “false” for a given page. Note that the second link checks multiple blog/post conditions (assuming that that is for the blog).

Leave a Reply

Your email address will not be published.

Back to top button