Add Dynamic Classes to Menu Items

Hire Now!

Whether you’re looking to launch your brand, showcase your portfolio, or open an online store, we’re here to bring your ideas to life.

  • Post Created: 1 week ago
  • Views: 1

Add Dynamic Classes to Menu Items

Reading Time: 1 Minute

Understanding the Hook: nav_menu_css_class

The nav_menu_css_class filter allows you to dynamically add or modify CSS classes for navigation menu items.

Why Use This Hook?

  • Highlight active pages or categories.
  • Add dynamic styles based on user actions.

How It Works

Append or modify the $classes array for each menu item.

Code Example

function add_dynamic_menu_classes($classes, $item, $args, $depth) {
    if (is_single() && $item->title === 'Blog') {
        $classes[] = 'current-menu-item';
    }
    return $classes;
}
add_filter('nav_menu_css_class', 'add_dynamic_menu_classes', 10, 4);

Discussion