You might have faced a scenario where you need to add CSS class into the lists and links in wp_nav_menu() during WordPress theme development, unfortunately, WordPress does not give an easier way to solve this issue.
This tutorial is going to illustrate how you can add CSS class to lists and links in wp_nav_menu()
How to Add CSS Class to lists and links in wp_nav_menu()
To add CSS class to menu lists in wp_nav_menu(), use the WordPress inbuild method nav_menu_link_attributes filter.
To add class to menu lists add the following code into your 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);
To add CSS class into your menu links in wp_nav_menu, add the following code into your funtions.php file.
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 );
The final step would add these filters to wp_nav_menu().
<?php wp_nav_menu(array( 'theme_location' => 'top-menu', 'menu_class' => 'nav navbar-nav mr-auto', 'add_li_class' => 'nav-item', "container" => false, "link_class" => "nav-link" )); ?>
add_list_class attribute adds specified class to lists in the menu and list_class attribute adds class to the links in the menu.
My name is Benson Karue, I was Software Engineer Telenet Co LTD before I quit and joined YouTube and Udemy as an instructor. I have real-world software experience and have a Bachelor’s degree in Mathematics and Computer Science with 6+ years of coding experience and winning several competitions and coding challenges.
I am familiar with C, C++, C#, Objective-C, Java, Swift, Android, iOS, Windows mobile, J2ME, Blackberry, HTML5, CSS3, JavaScript, Jquery, AJAX, Node.js, PHP, Ruby, Python, Scala, Groovy, PhoneGap JSP, JSF, EJB, Struts, Hibernate and Spring MVC, Flat Design along with databases such as MySQL, Oracle, SQLServer, SQLite and many other technologies and frameworks