Welcome Guest! Login? Checkout
This post was written 9 months ago and therefore may not be as accurate as more recent posts.

Recently we’ve had an issue on one of our sites whereby we had a post archive on a WordPress menu. When the page was shown, then the active class would be shown on the site, and styled accordingly. The problem occurred was when we switched from the archive to the individual post, and the menu item lost it’s “active” class, which looked a little bit odd. So we’d have to make sure the “active” class is shown, we’d have to use a bit of jQuery. This post will show you how to add active class in wp_nav_menu in WordPress.

Get the Menu Item ID you wish to Target

To begin with, you need to grab the menu item ID. To do this in Google Chrome, click the menu element you wish to target and then Inspect Element. You should see something like this.

get-menu-item-id

 

Grab the menu item (in this example, “menu-item-149“), and remember this for later.

The WordPress PHP

Next we need to look at the PHP. We will be using the wp_localize_script() function, that will allow variables to be passed into JavaScript files. Here is the code.

What this function does is check if the current page we’re looking at is a single post, if it is single, we register a script (more on that later), and the create an array with one index ‘liid’, which contains the Menu Item ID we’re looking to target. We then localise the script using this array, and then enqueue the script.

The jQuery

You will see the ‘active-menu-item.js‘ mentioned in the code, well what does that contain? Well it’s a small JavaScript file, that contains the following.

What this does is that it takes the menu_to_target.liid variable (which is menu-item-149), and adds a class of ‘current-menu-item‘ for this menu item.

Most themes have stylings for this menu item, so you should be good to go.

A Word of Warning

I feel this way is a bit of a hack, and this post is a bit of a cry for help. There must be a better way of doing it. If you do know one, please share in the comments!

 
 
 

Comments

Polite Disclaimer: I am welcome, open and willing for corrections to be shared in the comments (with corrections being added to posts and credited), and the comments field should be used to promote discussion and make this post better. I do not know everything and if anybody finds a better way to do something, then by all means please share it below.

However, I'm unable to offer support to posts. The reason being is that WordPress has tens of thousands of plugins and millions of themes. As such, finding out exactly why code doesn't work with your setup is a long process. If you wish for me to look at your code, please use the priority support area.

Comments asking support will be left on the site, but there is no guarantee of answer.

    Comments are closed.