Return only top-level navigation items from a menu using wp_get_nav_menu_items

Let’s take a look at wp_get_nav_menu_items code reference.

It takes two parameters:

  • $menu – (int|string|WP_Term) (Required) Menu ID, slug, name, or object,
  • $args – (array) (Optional) Arguments to pass to get_posts().

So we can use get_posts args in here… And if we want to get only top-level posts, then post_parent arg comes useful…

So something like this should do the trick:

function cr_get_menu_items($menu_location)
{
    $locations = get_nav_menu_locations();
    $menu = get_term($locations[$menu_location], 'nav_menu');
    return wp_get_nav_menu_items($menu->term_id, array('post_parent' => 0));
}

Leave a Comment