How to add (css) classes to only one wp_nav_menu()?

Edit

I removed the original Question as this Q has far above 1.000 views now – which means it’s important to a lot of people – to show you something that works a) without a custom Walker & b) is easy. Note: I only removed to original Q, because it was pretty unspectacular.

The Task

Add css classes to all nav menu items inside a specific Nav Menu that was added via (admin UI) Appearance > Menu.

The function

function wpse4388_navmenu_classes( $items, $menu, $args )
{
    // prevent crashing the appearance > menu admin UI
    if ( is_admin() )
        return;

    # >>>> start editing

        // Nav menu name you entered in the admin-UI > Appearance > Menus (Add menu).
        $target['name'] = 'Topnav';

        // A targeted menu item that needs a special class - add the item number here
        $target['items'] = array( (int) 6 );

    # <<<< stop editing

    // filter for child themes: "filter_nav_menu_{nav menu name}"
    // the nav menu name looses all empty spaces and is set to lower
    // if you want to use the filter, hook your child theme function into 'after_setup_theme'
    $target = apply_filters( 'filter_nav_menu_'.strtolower( str_replace( " ", "", $target['name'] ), $target );

    // Abort if we're not with the named menu
    if ( $menu->name !== $target['name'] ) 
        return;

    foreach ( $items as $item )
    {
        // Add the class for each menu item
        $item->classes="classes for all items";

        // Append this class if we are in one of the targeted items
        if ( in_array( (int) $item->menu_order, $target['items'] ) )
            $item->classes .= ' only for a single item';
    }

    return $items;
}
add_filter( 'wp_get_nav_menu_items', 'wpse4388_navmenu_classes', 10, 3 );

Was it helpful? Don’t forget to vote up! 🙂

4 Answers
4

I’m going to start by saying something similar to Horttcore..

Is there a reason you can’t simply provide a differing container element for the given menu, it should provide enough specificity to style it uniquely.

Although, you could do something like this to conditionalise menu args based on the menu’s location..

function my_wp_nav_menu_args( $args="" ) {
    if( $args['theme_location'] == 'your-specific-location' )
        $args = array_merge( array(
            'container_class' => 'example',
            'menu_class' => 'example2'
        ), $args );
    return $args;
}
add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );

Above code is based on the example given on the codex page for wp_nav_menu, and could easily be extended to do any number of things.
http://codex.wordpress.org/Function_Reference/wp_nav_menu

Hope that helps..

Leave a Comment