Develop

WordPress: Adding Custom Classes to wp_nav_menu

The Issue

In WordPress, there is a handy function that displays custom menus that are setup in Appearance > Menus, that function is wp_nav_menu();. If you are setting up your menus this way (and you should be) I’m sure you are familiar with some of the limitations of what is output on the page. From a design standpoint, these menus can be rather difficult to work with.

There are a few ways to alter the code that is spit out, one of those (and arguably the most powerful way) would be to use a Custom Walker Function…but that’s another beast for another day.

A lot of the time, all we need are some specific classes on certain menu items in order to achieve what we need.

Classy

fig 1.0 classy

Example

As an example, I’m going to show you how to setup a “split menu”, where the site’s logo is centered and has three menu items on either side. This is a popular layout, but impossible* to achieve without some additional classes.

*I’m aware you can use something like :nth-child(), but for those of us supporting older browsers and for other instances where you need classes, that solution isn’t always ideal.

Solution

We are going to add a simple function to either your functions.php file, or a custom functionality plugin if you’re using one.

The code below does the following:

  1. If the menu item is item number “three”, it will get a class of “large-margin” — this way you can add a right margin to the menu item that is as wide or wider than the logo you are passing over.
  2. If the menu item comes after the third menu item, it will get a class of “right-menu” — with this you can target the right menu items and adjust those margins or text alignments specifically.
function custom_nav_class($classes, $item){

    	if ( $item->menu_order == 3 ) {
    		$classes[] = "large-margin";
      	}
      	if ( $item->menu_order > 3 ) {
        	$classes[] = "right-menu";
      	}
      	return $classes;
    }

    add_filter('nav_menu_css_class' , 'custom_nav_class' , 10 , 2);

Conclusion

You can play around with this. If you need more menu items to the right/left just adjust the numbers in the function. I have had this function come in  handy a few times, so I hope you can get some use out of it.

{ Respond }

Leave a response