0

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 );
  • 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. – Prasad Nevase Feb 21 '16 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 '16 at 11:55
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 );
  • Any idea why my $args variable is an empty array? – benedict_w Mar 29 at 12:08

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.