ADVERTISEMENT
How to add CSS class to li and _a_ in wp_nav_menu

How to add CSS class to li and links in wp_nav_menu

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.

 



AdBlock Detected!
This site depends on revenue from ad impressions to survive. If you find this site valuable, please consider disabling your ad blocker or pausing adblock for this website.