How to add Class in li using functions in wordpress

Sometimes you need to customize the default wordpress menu system to add your own set of css classes. WordPress provides a couple of filters to do that.

I use these snippets to add custom classes to list items and menu links in wordpress. Paste these in your functions.php file or your plugin file to make this work.

/* Add custom classes to list item "li" */

function _namespace_menu_item_class( $classes, $item ) {       
    $classes[] = "nav-item"; // you can add multiple classes here
    return $classes;
} 

add_filter( 'nav_menu_css_class' , '_namespace_menu_item_class' , 10, 2 );

To add multiple classes to the list item, just assign the additional classes to $classes[] array as below
* Add more custom classes to list item “li” */
function _namespace_menu_item_class( $classes, $item ) {       
    $classes[] = "nav-item";
    $classes[] = "another-class"; 
    $classes[] = "more-custom-class";
    return $classes;
} 

Adding custom class to the menu link is a bit tricky as there is no hook or filter to work with the “a” element directly. So we will take a roundabout way and use a string replace function

/* Add custom class to link in menu */

function _namespace_modify_menuclass($ulclass) {
    return preg_replace('/<a /', '<a class="nav-link"', $ulclass);
}

add_filter('wp_nav_menu', '_namespace_modify_menuclass');

What we are doing here is adding a filter function to wp_nav_menu which returns the whole menu block and then replacing the “a” element with a desired class.

Leave a Reply

Your email address will not be published. Required fields are marked *