Skip to content

Instantly share code, notes, and snippets.

@hitautodestruct
Forked from anonymous/gist:4344870
Last active September 26, 2022 11:25
Show Gist options
  • Save hitautodestruct/4345363 to your computer and use it in GitHub Desktop.
Save hitautodestruct/4345363 to your computer and use it in GitHub Desktop.
Generate a custom structure for Wordpress menus.

This gist is for showing an example of a custom wordpress menu.

If you want to get more from the menu item simply have a look at the $item object. i.e:

// Will return a large object with lots of props like title, url, description, id etc.
var_dump( $item );

This code works on Wordpress 4.1.1 as of 31st of March 2015

<?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 ):
$link = $item->url;
$title = $item->title;
// 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 $title; ?>
</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 $title; ?></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; ?>
</ul>
</nav>
@mehmetsarr
Copy link

<?= $page->post_title ?>

this is not happening. main code becomes but dropdown icon disappears

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