Quantcast
Channel: Devils Workshop » wp_nav_menu
Viewing all articles
Browse latest Browse all 2

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

$
0
0

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’.

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.

-- This Post Add custom CSS classes to wp_nav_menu’s HTML output using WordPress filters is Published on Devils Workshop .


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images