Add custom CSS classes to wp_nav_menu’s HTML output using WordPress filters

WordPress has a great feature called ‘filter’ with which we can add our own classes to nav menu items.  Most times you need to add classes in nav menu items on some conditions.

For example, in menu you have ‘sample ‘ category item. You have to add class to this item if your single post is of ‘sample’ category or its categories have parent category as  ‘sample’. You can easily add class by using ‘nav_menu_css_class’ filter.

add_filter(‘nav_menu_css_class’ , ‘rt_nav_special_class’ , 10 , 2);

‘nav_menu_css_class’ is name of the filter to hook our function  ‘rt_nav_special_class’.

ADVERTISEMENT

10 is the priority of the function and 2 is the number of arguments the function accepts. Now you may write your condition in ‘rt_nav_special_class’ to add class to menu item.

function rt_nav_special_class($classes, $item){
     if(your condition){ //example: you can check value of $item to decide something...
             $classes[] = “special”;
     }
     return $classes;
}

rt_nav_special_class() accepts two arguments $classes and $item. $classes is an array contains class name already assigned by wp_nav_menu. We can add our classes in this array. I am added ‘special’ as class name. $item is current nav menu item to which we are adding a class.

If you var_dump this $item you will get all information about the current nav menu item. Using this $item you can any condition you want. Below is screen shot of our ‘special’ class in nav menu item in Firebug.

I hope you get what I explained to you. If you have any queries or suggestions do write in your comments.

Published by [email protected]

I like Wordpress. Developed many Wordpress themes and plugins.

11 replies on “Add custom CSS classes to wp_nav_menu’s HTML output using WordPress filters”

  1. Yes, luis you can change current class to that you want.
    I am used this filter when I want different colors for each parent menu item and corresponding children item.

  2. I tried this and it doesn’t work:

    function rt_nav_special_class($classes, $item){
    if(is_function()){ //example: you can check value of $item to decide something…
    $classes[] = ‘box-right-thinnest’;
    }
    return $classes;
    add_filter(‘nav_menu_css_class’ , ‘rt_nav_special_class’ , 10 , 2);

    1. Chris, If you want to add class to all li, no need to check any condition. I give you simple solution. Here i added special class to each li.

      add_filter(‘nav_menu_css_class’ , ‘rt_nav_special_class’ , 10 , 2);

      function rt_nav_special_class($classes, $item){

      $classes[] = “special”;

      return $classes;
      }

  3. Sorry the code is not display,
    I need to add class red to the nav menu li class. The class already have name menu-item-44. How i check the conition for add class?
    I need exact condition example using $item.
    Please help.

Comments are closed.