Skip to content

Instantly share code, notes, and snippets.

@tuguchev-andrey
Forked from hitautodestruct/readme.md
Last active May 3, 2022 13:17
Show Gist options
  • Select an option

  • Save tuguchev-andrey/a2f9a20985a495d73e2f09d711d305d5 to your computer and use it in GitHub Desktop.

Select an option

Save tuguchev-andrey/a2f9a20985a495d73e2f09d711d305d5 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 multi-level 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 5.9.3 as of 3rd of May 2022

Example of my multi-level menu:

image

<?php
$menu_name = 'Main Menu';
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object( $menu_name );
$menuitems = wp_get_nav_menu_items( $menu->term_id, array( 'order' => 'DESC' ) );
?>
<nav class="custom-mobile-menu">
<ul class="main-nav">
<?php
$count = 0;
$submenu = false;
$category_level_UL_tag_closed = true;
$count_exclude_Arr = [];
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>
<?php if($menuitems[$count + 1]->menu_item_parent != $menuitems[$count]->ID): ?>
</ul>
<?php $submenu = false; ?>
<?php else: ?>
<ul class="sub-menu sub-sub-menu">
<?php for($i= $count + 1; $i<= count($menuitems); $i++) : ?>
<?php if ($menuitems[ $i ]->menu_item_parent == $menuitems[ $count ]->ID) : ?>
<li class="item">
<a href="<?php echo $menuitems[ $i ]->url; ?>" class="title"><?php echo $menuitems[ $i ]->title; ?></a>
</li>
<?php $count_exclude_Arr[] = $i - 1;
$category_level_UL_tag_closed = false;
endif;
if($i == count($menuitems)): ?>
</ul>
</li><!-- category level closed -->
<?php endif; ?>
<?php endfor; ?>
<?php endif; ?>
<?php endif; ?>
<?php if ( $menuitems[ $count + 1 ]->menu_item_parent != $parent_id
&& !in_array($count, $count_exclude_Arr) ): ?>
<?php if(!$category_level_UL_tag_closed ): ?>
</ul> <!-- main level sub-menu closed -->
<?php $category_level_UL_tag_closed = true; endif; ?>
</li> <!-- top level li closed -->
<?php $submenu = false; endif; ?>
<?php $count++; endforeach; ?>
</ul>
</nav>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment