Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Class in <li> using wp_nav_menu() in Wordpress?

I am using wp_nav_menu($args) and I want to add my_own_class CSS classname to the <li> element.

I'd like to get the following result:

<li class='my_own_class'><a href=''>Link</a> 

How to do that?

like image 941
Ayyaz Zafar Avatar asked Jan 22 '13 17:01

Ayyaz Zafar


People also ask

How do I add a class to a tag in wp nav menu?

Show activity on this post. function add_menu_link_class( $atts, $item, $args ) { if (property_exists($args, 'link_class')) { $atts['class'] = $args->link_class; } return $atts; } add_filter( 'nav_menu_link_attributes', 'add_menu_link_class', 1, 3 );


1 Answers

No need to create custom walker. Just use additional argument and set filter for nav_menu_css_class.

For example:

$args = array(     'container'     => '',     'theme_location'=> 'your-theme-loc',     'depth'         => 1,     'fallback_cb'   => false,     'add_li_class'  => 'your-class-name1 your-class-name-2'     ); wp_nav_menu($args); 

Notice the new 'add_li_class' argument.

And set the filter on functions.php

function add_additional_class_on_li($classes, $item, $args) {     if(isset($args->add_li_class)) {         $classes[] = $args->add_li_class;     }     return $classes; } add_filter('nav_menu_css_class', 'add_additional_class_on_li', 1, 3); 
like image 157
Zunan Avatar answered Sep 28 '22 06:09

Zunan