0

While building a custom theme, I've been stuck on how to add a CSS class to a certain theme menu (meaning a custom menu that is associated with a theme menu position).

So far, in my template I have

  <?php if (has_nav_menu('main-menu')) : ?>
    <nav class="topmenu" role="navigation">
    <?php
      wp_nav_menu(array(
        'menu-class'  => 'topmenu--list',
        'theme_location' => 'main-menu',
        'fallback_cb' => false,
      ));
    ?>
    </nav>
   <?php endif; ?>

So, I'm sort of missing a 'menu-item-class' option in the wp_nav_menu's $args array. How can I pass a CSS class to each menu item?

Just to be clear, I do not want an editor to set a CSS class to each menu item manually in admin backend. I want to add the CSS class to each menu item programmatically.

1

You can use the nav_menu_css_class filter which is applied to every menu item in the specified nav menu.

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

function special_nav_class($classes, $item){
    $classes[] = 'your-custom-class';
    return $classes;
}

More info: http://www.wpbeginner.com/wp-tutorials/add-a-custom-class-in-wordpress-menu-item-using-conditional-statements/

| improve this answer | |
0

From WordPress Plugin API You can use nav_menu_css_class filter example :

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 );

https://codex.wordpress.org/Plugin_API/Filter_Reference/nav_menu_css_class

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.