Add Custom CSS Classes to WordPress Nav Menu Items

·

2 min read

·

WordPress generates CSS classes on each nav menu item automatically, but sometimes you need to add your own — for custom styling, JavaScript hooks, or conditional logic. The nav_menu_css_class filter makes this straightforward.

The Filter

Add this to your functions.php. The filter receives the array of CSS classes and the menu item object for each item in the menu:

add_filter( 'nav_menu_css_class', function( $classes, $item ) {
    // Add a class to a specific menu item by title.
    if ( 'Contact' === $item->title ) {
        $classes[] = 'menu-cta';
    }

    return $classes;
}, 10, 2 );

This adds the menu-cta class to the Contact menu item, which you can then style differently — as a button, a highlighted link, or whatever the design calls for.

Other Matching Options

You’re not limited to matching by title. The $item object gives you access to:

// Match by menu item ID.
if ( $item->ID === 42 ) { ... }

// Match by URL.
if ( str_contains( $item->url, '/portfolio/' ) ) { ... }

// Match by object type (page, post, category, custom).
if ( 'page' === $item->object ) { ... }

// Add a class to all top-level items.
if ( 0 === (int) $item->menu_item_parent ) {
    $classes[] = 'top-level';
}

Quick Note

WordPress already adds useful classes to menu items: current-menu-item, current-menu-ancestor, menu-item-type-post_type, etc. Check the generated HTML before adding custom classes — what you need might already be there.

Leave a comment