WordPress automatically outputs many helpful CSS class names for menus. If you use the wp_nav_menu()
function to display your menus, as all good themes should do, you don’t have to settle for just the default class names.
The wp_nav_menu()
function calls the wp_nav_menu_objects
filter, which allows you to manipulate the menu objects before being converted into HTML and displayed on the site. One of the things you can do is add a few custom class names, like this:
// Add extra classes for the first and last items in all WordPress menus
add_filter( 'wp_nav_menu_objects', function ( $items ) {
if ( ! empty( $items ) ) {
$items[1]->classes[] = 'menu-item-first';
$items[ count( $items ) ]->classes[] = 'menu-item-last';
}
return $items;
} );
This adds a menu-item-first
class to the first menu item and a menu-item-last
class to the last menu item. These extra utility classes are helpful when styling menus in a custom theme.