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

Sayan Dey

Sayan Dey / January 12, 2023

1 min read––– 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:

function add_li_class($classes, $item, $args) {
    $classes[] = 'my-custom-class';
    return $classes;
}
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:

function add_a_class($atts, $item, $args) {
    $atts['class'] = 'my-custom-class';
    return $atts;
}
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.

- subscribers – View all issues