DEV Community

Dhimas Kirana
Dhimas Kirana

Posted on

How to Add Class to <li> tag on wp_nav_menu

Hello, dev.. πŸ‘‹

In this tutorial, we will try to add a class list tag (<li>) to the WP Nav Menu

<?php

add_filter('nav_menu_css_class', 'add_class_li_tag', 1, 3);
function add_class_li_tag($classes, $item, $args) {

    // Conditional if class li tag is different at different menu locations
    if ($args->theme_location == 'menu-footer') {
        $classes[] = 'list-inline-item';
    } else {
        $classes[] = 'nav-item';
    }

    // Conditional if the active page is given a class
    if (in_array('current-menu-item', $classes)) {
        $classes[] = 'active ';
    }

    // Return the modified class
    return $classes;
}
Enter fullscreen mode Exit fullscreen mode

OK, I'll explain so you don't just copy it without understanding your coding needs.

To modify the class in the tag list we will use the nav_menu_css_class filter. We will push the modified class to the $classes array using the square bracket method ( $classes[] )

Different classes at different menu locations

In line 7 I provide a conditional if the menu location is "menu-footer" then use the class "list-inline-item". Apart from that, use the "nav-item" class

So adjust it to your needs. If you only use 1 menu, the if conditional is lost.

Class on the active menu

In line 14, conditional if there is a class "current-menu-item" meaning the menu that is opened is currently active. So, usually on the active menu, we will add the "active" class according to the CSS styling that we created.

Adding Class to Link Tag

So, this is to add a class to the <a href="#"> link tag on the menu.

<?php

add_filter('nav_menu_link_attributes', 'add_class_link', 10, 2);
function add_class_link($classes, $item) {

    // Add class
    $classes['class'] = 'nav-link';

    // Add class 'active' if the page is currently active
    if (in_array('current_page_item', $item->classes)) {
        $classes['class'] = 'nav-link active';
    }

    return $classes;
}
Enter fullscreen mode Exit fullscreen mode

So that's it for the tutorial, if you have any questions, write them in the comments column.

Good luck 🍻

Top comments (0)