How to add Class in <li> using wp_nav_menu() in Wordpress?
You can add a filter for the nav_menu_css_class
action in your functions.php file.
Example:
function atg_menu_classes($classes, $item, $args) {
if($args->theme_location == 'secondary') {
$classes[] = 'list-inline-item';
}
return $classes;
}
add_filter('nav_menu_css_class', 'atg_menu_classes', 1, 3);
Docs: https://developer.wordpress.org/reference/hooks/nav_menu_css_class/
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);