How do I generate a custom menu/sub-menu system using wp_get_nav_menu_items in WordPress?

For anyone who tackles something similar here’s my solution:

Quick code example on a gist

Here’s the code on a github gist for anyone who wants to get in on the copy paste action.

TL;DR

TL;DR Loop over list, drill down if there’s a sub menu, close if we reach the end of the sub menu and menu.

Complete Code explanation

Firstly get the menu items as a flat array:

<?php
$menu_name="main_nav";
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
$menuitems = wp_get_nav_menu_items( $menu->term_id, array( 'order' => 'DESC' ) );
?>

Then iterate over the array of the menu items:

<nav>
<ul class="main-nav">
    <?php
    $count = 0;
    $submenu = false;

    foreach( $menuitems as $item ):
        // set up title and url
        $title = $item->title;
        $link = $item->url;

        // item does not have a parent so menu_item_parent equals 0 (false)
        if ( !$item->menu_item_parent ):

        // save this id for later comparison with sub-menu items
        $parent_id = $item->ID;
    ?>

Write the first parent item <li>:

    <li class="item">
        <a href="https://stackoverflow.com/questions/11935423/<?php echo $link; ?>" class="title">
            <?php echo $title; ?>
        </a>
    <?php endif; ?>

Check that this items’ parent id matches the stored parent id:

        <?php if ( $parent_id == $item->menu_item_parent ): ?>

Start sub-menu <ul> and set $submenu flag to true for later referance:

            <?php if ( !$submenu ): $submenu = true; ?>
            <ul class="sub-menu">
            <?php endif; ?>

Write the sub-menu item:

                <li class="item">
                    <a href="https://stackoverflow.com/questions/11935423/<?php echo $link; ?>" class="title"><?php echo $title; ?></a>
                </li>

If the next item does not have the same parent id and we have a sub-menu declared then close the sub-menu <ul>

            <?php if ( $menuitems[ $count + 1 ]->menu_item_parent != $parent_id && $submenu ): ?>
            </ul>
            <?php $submenu = false; endif; ?>

        <?php endif; ?>

Again, if the next item in the array does not have the same parent id close the <li>

    <?php if ( $menuitems[ $count + 1 ]->menu_item_parent != $parent_id ): ?>
    </li>                           
    <?php $submenu = false; endif; ?>

<?php $count++; endforeach; ?>

  </ul>
</nav>

Leave a Comment