Support » Developing with WordPress » Display menu with child items

  • Hi all,

    this may seem a simple question but I can’t figure out how to display menu child items properly. This is what I have:

    <?php 
    if ( $menu_items = wp_get_nav_menu_items( 'my-menu-name' ) ) {
      foreach ( $menu_items as $menu_item ) {
        echo '<li><a href="' . $menu_item->url . '">' . $menu_item->title . '</a></li>';
      }
    }
    ?>

    The code works as it simply loops through the menu. However, it will echo out all the menu items without considering if an item is a child.

    Menu structure in WP dashboard:

    - Main item 1
    - Main item 2
      - Child item 1
      - Child item 2
    - Main item 3

    Result on page:

    - Main item 1
    - Main item 2
    - Child item 1
    - Child item 2
    - Main item 3

    So basically all items are flattened out. How can I change the foreach loop so that PHP can tell if $menu_item is a child with the corresponding parent?

    • This topic was modified 2 months, 2 weeks ago by avengerzz.
Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator t-p

    (@t-p)

    I recommend asking at your theme’s dedicated support so the theme’s developers and support community can help you with this.

    Thread Starter avengerzz

    (@avengerzz)

    @t-p I’m creating my own theme.

    You should use core functionality instead of writing your own: https://developer.wordpress.org/reference/functions/wp_nav_menu/
    Since the menu is a nested list, it needs a walker to output it correctly. You can substitute a different walker, but the core one is very good. You can extend the core walker class to override a function or two if you need to adjust the output HTML, but there are also filters where you can affect various parts.

Viewing 3 replies - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.