3

Is there a way to determine which theme placement a menu is for when modifying it with the wp_get_nav_menu_items filter hook?

I'd like to only add items to certain menus and I don't want to have to depend on the ID or the name of the menu.

1 Answer 1

2

Not sure this is the simplest means, but you could conditionally add the filter to just the location you want to modify via wp_nav_menu_args filter when wp_nav_menu is called, then immediately remove the filter so it isn't applied to other menus.

function wpa108544_nav_menu_args( $args ){
    // check if it's the location we want the filter applied to
    if( 'primary' == $args['theme_location'] )
        add_filter( 'wp_get_nav_menu_items', 'wpa108544_get_nav_menu_items', 10, 3 );

    return $args;
}
add_filter( 'wp_nav_menu_args', 'wpa108544_nav_menu_args' );


function wpa108544_get_nav_menu_items( $items, $menu, $args ){
    // remove the filter
    remove_filter( current_filter(), __FUNCTION__, 10, 3 );

    // do your menu manipulation stuff here
}
4
  • To me that seems too much of a hack and creates brittle code. Why isn't the args from wp_nav_menu_args used for wp_get_nav_menu_items? Commented Aug 1, 2013 at 11:44
  • Brittle in what way? Describe a scenario where this would not work for you. In some cases there are no nav menu args, wp_get_nav_menu_items isn't necessarily called via wp_nav_menu.
    – Milo
    Commented Aug 1, 2013 at 15:11
  • Brittle because its just a very poor design. Commented Aug 1, 2013 at 17:21
  • if you'd care to explain actual, practical issues with it, perhaps we can come up with a better solution.
    – Milo
    Commented Aug 1, 2013 at 17:26

Your Answer

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

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