title: How to display 3 levels of hierarchical menu in WordPress using "wp_get_nav_menu_items"?
body: <p>I am trying to display 3 levels of hierarchical menu in WordPress 
  using wp_get_nav_menu_items function, but somehow the structure is not
  displaying in that manner.</p>
  
  <p>This is my code which I have included in header file, but the structure is not proper.</p>
  
  <pre><code>$menu_name = 'primary-menu'; 
       $locations = get_nav_menu_locations(); 
       $menu = wp_get_nav_menu_object($locations[$menu_name]); 
       $menuitems = wp_get_nav_menu_items($menu-&gt;term_id, array('order' =&gt; 'DESC')); 
       $ParentArray = array(); 
       foreach ($menuitems as $item) { 
         // if (!empty($item-&gt;menu_item_parent) &amp;&amp; !in_array($item-&gt;menu_item_parent, $ParentArray)) { 
               array_push($ParentArray, $item-&gt;ID); 
          // } 
       }
        ?&gt;
  
  &lt;nav&gt;
    &lt;ul class="main-nav"&gt;
      &lt;?php 
          $count = 0; 
          $submenu = false; 
          foreach ($menuitems as $item): 
              $link = $item-&gt;url; 
              $title = $item-&gt;title; 
              // item does not have a parent so menu_item_parent equals 0 (false) 
              if (!$item-&gt;menu_item_parent): 
                  // save this id for later comparison with sub-menu items 
                  $parent_id = $item-&gt;ID; 
                  ?&gt;
  
      &lt;li class="item"&gt;
        &lt;a href="
          &lt;?php echo $link; ?&gt;" class="title"&gt;
          &lt;?php echo $title; ?&gt;
        &lt;/a&gt;
        &lt;?php endif; ?&gt;
        &lt;?php if (in_array($item-&gt;menu_item_parent, $ParentArray)): ?&gt;
        &lt;?php if (!$submenu): $submenu = true; ?&gt;
        &lt;ul class="sub-menu"&gt;
          &lt;?php endif; ?&gt;
          &lt;li class="item"&gt;
            &lt;a href="
              &lt;?php echo $link; ?&gt;" class="title"&gt;
              &lt;?php echo $title; ?&gt;
            &lt;/a&gt;
          &lt;/li&gt;
          &lt;?php if (!isset($menuitems[$count + 1]) || $menuitems[$count + 1]-&gt;menu_item_parent != $parent_id &amp;&amp; $submenu): ?&gt;
        &lt;/ul&gt;
        &lt;?php 
            $submenu = false; 
            endif; 
            ?&gt;
        &lt;?php endif; ?&gt;
        &lt;?php if (!isset($menuitems[$count + 1]) || $menuitems[$count + 1]-&gt;menu_item_parent != $parent_id): ?&gt;
      &lt;/li&gt;
      &lt;?php 
          $submenu = false; 
          ?&gt;
      &lt;?php 
          $count++; 
          endforeach; 
          ?&gt;
    &lt;/ul&gt;
  &lt;/nav&gt;
  </code></pre>