Given a nav_menu_item object, how would I determine the name of the Menu it is associated with?

I have a couple menus defined in my theme, as well as, a nav_menu_css_class filter. Inside the filter, I only want to add classes to one of the menus. If I can dynamically pull the menu name using the $item variable I can make sure I'm only acting on a specific menu.


The third argument passed to the filter are the $args used for wp_nav_menu:

function wpse_147499_nav_menu_css_class( $classes, $item, $args ) {
     print_r( $args );

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

...which gives you:

stdClass Object
    [menu] => 
    [container] => 
    [container_class] => 
    [container_id] => 
    [menu_class] =>
    [menu_id] => 
    [echo] => 1
    [fallback_cb] => 
    [before] => 
    [after] => 
    [link_before] => 
    [link_after] => 
    [items_wrap] =>
    [depth] => 0
    [walker] => 
    [theme_location] =>

Obviously the values of these vary, and never assume that one will always be non-empty - but hopefully you should be able to differentiate between menus.

  • Thank You!! This worked perfectly. I'll come back and mark as the accepted answer once my rep has increased.
    – CodeSmith
    Jun 4 '14 at 15:45
  • @CodeKing please revisit all your questions and accept answers that should be accepted answers. You don't need any reputation to accept an answer to your questions. You also gain reputation for accepting an answer to your questions and there is a badge as well. Thank you Oct 19 '14 at 5:49

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.