How to add <li> class using wp_nav_menu() in WordPress?

Sayan Dey

Sayan Dey / January 12, 2023

1 min readNaN views

In order to add a class to the <li> elements and/or the <a> elements in the wp_nav_menu() function, you will need to use the nav_menu_css_class and link_attributes filter hooks.

Add a class to the <li> element in the WordPress navigation menu.

Here is an example of how you can add a class to the <li> elements:

functions.php

_10
function add_li_class($classes, $item, $args) {
_10
$classes[] = 'my-custom-class';
_10
return $classes;
_10
}
_10
add_filter('nav_menu_css_class', 'add_li_class', 1, 3);

You will need to call wp_nav_menu() after this code is added to your functions.php

Add a class to the <a> element in the WordPress navigation menu.

Here is an example of how you can add a class to the <a> elements:

functions.php

_10
function add_a_class($atts, $item, $args) {
_10
$atts['class'] = 'my-custom-class';
_10
return $atts;
_10
}
_10
add_filter('nav_menu_link_attributes', 'add_a_class', 1, 3);

Again, you will need to call wp_nav_menu() after this code is added to your functions.php

Make sure to replace the string "my-custom-class" with the class you want to add.

Conclusion

I hope this helps! Let me know if you have any questions on Guestbook. Subscribe to my weekly newsletter for more WordPress tutorials like this.

Subscribe to the newsletter

Get emails from me about web development, tech, and early access to new articles.

NaN subscribers – View all GitHub issues