• I’m working with custom menus, and defined a few locations in the theme’s functions.php file, and then through the admin defined some menus and assigned them to the locations.

    I just spent some time looking through the nav-menu.php in wp-includes/ and I can’t figure out how to pragmatically get the name of the menu assigned to a given location.

    I.e. if the theme registers a location called “header_menu” and I make a menu in admin called “navigation” and assign it to “header_menu”. How do I pragmatically get the menu assigned to that location (pass in “header_menu” and get out “navigation”)?

    Thanks,
    -Nate

Viewing 2 replies - 1 through 2 (of 2 total)
  • The three functions you’ll need to use are these:

    • get_registered_nav_menus()
    • wp_get_nav_menus()
    • get_nav_menu_locations()

    get_registered_nav_menus: This will give you a list of locations. The array keys will be the location slugs, and the array values will the location names.

    wp_get_nav_menus: This will give you a list of menus the (presumably) the user created. The array will be full of objects. These are really just taxonomies.

    get_nav_menu_locations: This will give you the information key to what you’re looking for. The keys of the returned array will be the location slug, and the values of the returned array will be the taxonomy IDs of menu.

    How to get the menu that belongs to a given location:

    $locations = get_registered_nav_menus();
    $menus = wp_get_nav_menus();
    $menu_locations = get_nav_menu_locations();
    
    $location_id = 'riddell-shop';
    if (isset($menu_locations[ $location_id ])) {
    	foreach ($menus as $menu) {
    		// If the ID of this menu is the ID associated with the location we're searching for
    		if ($menu->term_id == $menu_locations[ $location_id ]) {
    			// This is the correct menu
    
    			// Get the items for this menu
    			$menu_items = wp_get_nav_menu_items($menu);
    
    			// Now do something with them here.
    			//
    			//
    			break;
    		}
    	}
    } else {
    	// The location that you're trying to search doesn't exist
    }

    I hope that helps.

    // pass the id of the menu into this function
    $nav_menu = wp_get_nav_menu_object(21);
    // then echo the name of the menu
    echo $nav_menu->name;
    // This way you can output the name of the menu (like above the menu) if you needed an easy way to change the title of the menu

    Is this what you had in mind?

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Getting menu name in a given location’ is closed to new replies.