-1

I want to add a custom CSS class to menu items. So far, I got it working by using the filter hook nav_menu_css_class. However, I want to add this class to items of a specific menu only. So, how must a condition look like to affect a specific menu (e.g. 'custom-menu' in theme_location 'footer_menu') only?

function add_footer_nav_item_class( $classes, $item ) {
  // I am looking for a condition here
  if ($item belongs to 'custom-menu'){
    $classes[] = "footer--menu-item";
    return $classes;
  }
}
add_filter( 'nav_menu_css_class' , 'add_footer_nav_item_class' , 10, 2 );
2
  • 1
    Quick question, why do you want to assign css classes programmatically? Just want to know whether you are aware that you can add css classes from backend menu management interface itself. If you are not able to see the CSS Classes input box for a menu, then open Screen Options pane on top of Edit Menu page and tick CSS Classes checkbox. Feb 21, 2016 at 14:53
  • Good question. I didn't know about this feature up to now :). However, now that I've checked this out, I'd still add CSS classes programmatically for the reason, that I save repeating myself for each menu entry.
    – Bunjip
    Feb 22, 2016 at 11:55

1 Answer 1

0

You just need the third argument $args, of which one of it's properties is theme_location:

function wpse_218377_nav_menu_css_class( $classes, $item, $args ) {
    if ( ! empty( $args->theme_location ) && $args->theme_location === 'custom-menu' ) {
        $classes[] = 'footer--menu-item';
    }

    // ALWAYS return, not from inside the if
    return $classes;
}

add_filter( 'nav_menu_css_class' , 'wpse_218377_nav_menu_css_class' , 10, 3 );
1
  • Any idea why my $args variable is an empty array?
    – benedict_w
    Mar 29, 2019 at 12:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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