Skip to content

Instantly share code, notes, and snippets.

Created December 20, 2012 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/4344870 to your computer and use it in GitHub Desktop.
Save anonymous/4344870 to your computer and use it in GitHub Desktop.
Generates a custom menu sub menu nav using wordpress wp_get_nav_items(). See the following for details: http://stackoverflow.com/questions/11935423/how-do-i-generate-a-custom-menu-sub-menu-system-using-wp-get-nav-menu-items-in-w/11948374#comment19273552_11948374
<?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' ) );
?>
<nav>
<ul class="main-nav">
<?php
$count = 0;
$submenu = false;
foreach( $menuitems as $item ):
// get page id from using menu item object id
$id = get_post_meta( $item->ID, '_menu_item_object_id', true );
// set up a page object to retrieve page data
$page = get_page( $id );
$link = get_page_link( $id );
// 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;
?>
<li class="item">
<a href="<?php echo $link; ?>" class="title">
<?php echo $page->post_title; ?>
</a>
<a href="<?php echo $link; ?>" class="desc">
<?php echo $page->post_excerpt; ?>
</a>
<?php endif; ?>
<?php if ( $parent_id == $item->menu_item_parent ): ?>
<?php if ( !$submenu ): $submenu = true; ?>
<ul class="sub-menu">
<?php endif; ?>
<li class="item">
<a href="<?php echo $link; ?>" class="title"><?php echo $page->post_title; ?></a>
<a href="<?php echo $link; ?>" class="desc"><?php echo $page->post_excerpt; ?></a>
</li>
<?php if ( $menuitems[ $count + 1 ]->menu_item_parent != $parent_id && $submenu ): ?>
</ul>
<?php $submenu = false; endif; ?>
<?php endif; ?>
<?php if ( $menuitems[ $count + 1 ]->menu_item_parent != $parent_id ): ?>
</li>
<?php $submenu = false; endif; ?>
<?php $count++; endforeach; ?>
@laukstein
Copy link

Add (array) in foreach( (array) $menuitems as $item ).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment