Get nav menu items by location

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;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Robbert Vermeulen

Need help from a WordPress expert?

I would love to hear about your project and how I can help you achieve your goals