Get nav menu items by location

Published Dec 14, 2017

WordPress default get_nav_menu_items() function uses the menu name as identifier to retrieve the right menu items. I think it is better to retrieve the menu items by location since the menu name is a value which can be changed in the database and the location is hardcoded in your functions.php file by registering the menu.

/**
 * Get nav menu items by location
 *
 * @param $location The menu location id
 */
function get_nav_menu_items_by_location( $location, $args = [] ) {
 
    // Get all locations
    $locations = get_nav_menu_locations();
 
    // Get object id by location
    $object = wp_get_nav_menu_object( $locations[$location] );
 
    // Get menu items by menu name
    $menu_items = wp_get_nav_menu_items( $object->name, $args );
 
    // Return menu post objects
    return $menu_items;
}
Discover and read more posts from Robbert Vermeulen
get started