I’m working on a WordPress site and need some help with the navigation menu. I’m using the wp_nav_menu() function to display the menu, but I want to add my own CSS class to each list item.
I’ve looked through the WordPress Codex, but I’m not sure which parameters or filters to use. Does anyone know how to add a custom class to the <li> elements in the menu?
I’d appreciate any tips or code examples that could help me solve this. Thanks in advance for your help!
Another approach you might consider is using the ‘wp_nav_menu_objects’ filter. This gives you more flexibility to modify menu items before they’re rendered. Here’s a snippet you can add to your functions.php:
function add_custom_class_to_menu($items, $args) {
foreach($items as &$item) {
$item->classes[] = 'custom_class';
}
return $items;
}
add_filter('wp_nav_menu_objects', 'add_custom_class_to_menu', 10, 2);
This method allows you to add classes based on specific conditions if needed. For instance, you could check $item->object_id to add classes only to certain menu items. It’s a bit more involved than the nav_menu_css_class filter, but it offers greater control over the menu structure.
This filter adds ‘custom_class’ to every menu item. If you need more control, you can modify the function to add the class conditionally based on menu location, item properties, etc.
Remember to clear your cache after making changes. This approach is clean and doesn’t require modifying core WordPress files, which is always a plus for maintainability.