Menu location by menu id or menu ID in start_el() Walker

I’m creating a custom walker menu where I’m adding custom fields to the menu items, but I would like the fields to be specific to menu locations. I can get all the menu locations with the menu ID’s assigned to them from:

$menu_locations = get_nav_menu_locations();

This outputs an array like:

array:2 [
  "main_nav" => 27
  "footer_nav" => 29
]

Or you can get all the menus but they don’t have the theme locations with:

$menus = get_terms('nav_menu');

This outputs an an object list like:

array:3 [
  0 => {#762
    +"term_id": "28"
    +"name": "Footer Menu"
    +"slug": "footer-menu"
    +"term_group": "0"
    +"term_taxonomy_id": "28"
    +"taxonomy": "nav_menu"
    +"description": ""
    +"parent": "0"
    +"count": "1"
  }
  1 => {#761
    +"term_id": "27"
    +"name": "Menu 1"
    +"slug": "menu-1"
    +"term_group": "0"
    +"term_taxonomy_id": "27"
    +"taxonomy": "nav_menu"
    +"description": ""
    +"parent": "0"
    +"count": "11"
  }
]

My question is: Can you get the menu location of a specific menu by ID / name / slug? Or can you get the menu location by menu ID?

4 Answers
4

You’ll find it much easier to control which fields are shown, by controlling which walker is used. Rather than trying to ‘toggle’ the fields inside the walker.

I also wanted to show a bunch of custom fields, and only show them on a menu at a particular menu location. So I used the following…

add_filter( 'wp_edit_nav_menu_walker', function( $walker, $menu_id ) {

    $menu_locations = get_nav_menu_locations();

    if ( $menu_locations['main_menu'] == $menu_id ) {
        return 'Walker_Nav_Menu_Custom';
    } else {
        return $walker;
    }

}, 10, 2); 

Leave a Comment