apply_filters( 'nav_menu_css_class', string[] $classes, WP_Post $item, stdClass $args, int $depth )

Filters the CSS classes applied to a menu item’s list item element.


Parameters Parameters

$classes

(string[]) Array of the CSS classes that are applied to the menu item's <li> element.

$item

(WP_Post) The current menu item.

$args

(stdClass) An object of wp_nav_menu() arguments.

$depth

(int) Depth of menu item. Used for padding.


Top ↑

More Information More Information

This filter hook called by the WordPress Walker_Nav_Menu class.

Usage in WP 3.0 / 3.1+ / 4.1+:

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

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

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

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

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

add_filter( 'nav_menu_css_class', 'filter_handler', 10, 4 ); 
?>

Top ↑

Source Source

File: wp-includes/class-walker-nav-menu.php

View on Trac



Top ↑

Changelog Changelog

Changelog
Version Description
4.1.0 The $depth parameter was added.
3.0.0 Introduced.

Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 1 content
    Contributed by Aamer Shahzad

    Apply classes to a specific menu (theme location). WordPress 4.1 or higher.

    function wpdocs_channel_nav_class( $classes, $item, $args ) {
    
    	if ( 'network-menu' === $args->theme_location ) {
    		$classes[] = "network-menu-item";
        }
    
    	return $classes;
    }
    add_filter( 'nav_menu_css_class' , 'wpdocs_channel_nav_class' , 10, 4 );
  2. Skip to note 3 content
    Contributed by stevenlinx

    Example code migrated from Codex:

    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 );
    
  3. Skip to note 4 content
    Contributed by stevenlinx

    Example migrated from Codex:

    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 must log in before being able to contribute a note or feedback.