WordPress.org

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Plugin API/Filter Reference/nav menu css class

Description

A filter hook called by the WordPress Walker_Nav_Menu class.

Usage

<?php 
/* WP 3.0+ */
function filter_handler$classes $item ){ ...... }

add_filter'nav_menu_css_class''filter_handler'10); 

/* WP 3.1+ */
function filter_handler$classes $item$args ){ ...... }

add_filter'nav_menu_css_class''filter_handler'10); 

/* WP 4.1+ */
function filter_handler$classes $item$args$depth ){ ...... }

add_filter'nav_menu_css_class''filter_handler'10); 
?>

Parameters

$classes
(array) (required) Nav menu item classes.
Default: None
$item
(object) (required) Nav menu item data object.
Default: None
$args
(array) (optional) Nav menu arguments. Added in 3.1
Default: None
$depth
(int) (optional) Depth of menu item. Used for padding. Added in 4.1
Default: None

Examples

The following example adds a unique CSS class to a single, specific nav menu item.

function my_special_nav_class( $classes, $item ) {

    if ( is_single() && $item->title == 'Blog' ) {
        $classes[] = 'special-class';
    }

    return $classes;

}

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

You can use information from the $args parameter to conditionally filter classes based on properties of the menu that contains the items.

function my_secondary_menu_classes( $classes, $item, $args ) {
    // Only affect the menu placed in the 'secondary' wp_nav_bar() theme location
    if ( 'secondary' === $args->theme_location ) {
        // Make these items 3-columns wide in Bootstrap
        $classes[] = 'col-md-3';
    }

    return $classes;
}

add_filter( 'nav_menu_css_class', 'my_secondary_menu_classes', 10, 3 ); 

Source Code

nav_menu_css_class() is located in wp-includes/nav-menu-template.php.

Changelog

Related

Navigation Menu

See Also

Plugin_API/Filter_Reference