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;

I'm Robbert Vermeulen. I document everything I learn and help thousands of people with coding WordPress. My site has no ads or sponsors. If you enjoy my content, please consider supporting what I do.


    No comments yet..

Leave a reply

Feel free to ask questions or make comments.