I have the following function in my project:

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

The function is used in my theme like this:

  <?php $nav = cr_get_menu_items('navigation_menu') ?>
  <?php foreach ($nav as $link): ?>
    <a href="https://wordpress.stackexchange.com/questions/301988/<?= $link->url ?>"><?= $link->title ?></a>
  <?php endforeach; ?>

This currently returns all navigation items present in my menu – parent/top-level and sub navigation. I am wondering how to alter this to exclude all sub navigation items. I only want to display the parent/top-level items.

2 Answers
2

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 Reply

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