A quick trick for forcing the WordPress current menu item without using javascript

When using wp_nav_menu you sometimes run into situations where you need to force the current menu item styling on an arbitrary menu element; ie. You want a category menu item to stay selected while you’re on a post belonging to that category. You can easily do this by manually adding the current-menu-item class with javascript but this has some drawbacks. First off, if js is disabled it obviously wont work at all. The other problem is that you may have the content first appear normal, then have the class applied a split second later. Depending on your level of OCD this is either unnoticeable/unimportant or a huge deal. Luckily there’s a super easy, purely css method to fix this.

The fix involves using post_class() and creating a style that you apply only to a specific menu item. You need to make sure post_class() is used on the menu’s parent element (if it isn’t already). That last point is important because you may already be using post_class() on whatever div wraps the loop, but in many themes the menu is in a separate div. If your theme falls into this category then you’ll need to make sure you add post_class() again to one of the elements that wraps your menu, in my case I added it to a div#nav-menu which wraps my menu.

Once you have post_class() sorted out this is the css you’ll use;

#nav-menu li.current-menu-item a,
#nav-menu.category-blog  li.menu-item-455 a{
	font-weight: 700;
}

When looking at that code you see 2 selectors. The first one is the basic selector that sets the style for the current menu item. The second selector takes this same rule and applies it to a specific menu item. The way it works is pretty simple. It first makes sure that the current page/post is in the ‘blog’ category (by way of the class added using post_class). If the category is ‘blog’ it applies the style to a specific menu item (item-455 in this case). The class ‘menu-item-455’ is automatically added to the LI by wp_nav_menu(). If you look at your page source you’ll see that every LI in your menu has a unique class.

And that’s it, a quick and easy trick to force menu items without using javascript and without meddling with custom walkers.