Skip to content

Instantly share code, notes, and snippets.

@mjot
Forked from hitautodestruct/readme.md
Last active November 27, 2018 20:18
Show Gist options
  • Save mjot/06cba267144a9716caf79c4ad4f2dce6 to your computer and use it in GitHub Desktop.
Save mjot/06cba267144a9716caf79c4ad4f2dce6 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.

function wecGenerateMenu($menu_name) {
$menu = wp_get_nav_menu_object($menu_name);
$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' ) );
$count = 0;
$content_ = "";
$submenu = false;
foreach($menuitems as $item){
$url = $item->url;
$title = $item->title;
$active = ( $item->object_id == get_queried_object_id() ) ? 'active' : '';
// Parent
if (!$item->menu_item_parent){
$parent_id = $item->ID;
$content_ .= '<li class="nav-item '.$active.'"><a class="nav-link" href="'.$url.'">'.$title.'</a>';
}
// Child
if ($parent_id == $item->menu_item_parent){
if (!$submenu ){ $submenu = true; }
$content_ .= '<ul class="sub-menu"><li class="item"><a href="'.$url.'" class="title">'.$title.'</a></li>';
if (!isset($menuitems[ $count + 1 ]) || $menuitems[ $count + 1 ]->menu_item_parent != $parent_id && $submenu){
$content_ .= '</ul>';
$submenu = false;
}
}
if (!isset($menuitems[ $count + 1 ]) || $menuitems[ $count + 1 ]->menu_item_parent != $parent_id){
$content_ .= '</li>';
$submenu = false;
}
$count++;
}
$content_ .= '</ul>';
return $content_;
}
<nav>
<ul>
<?php echo wecGenerateMenu('nav_main'); ?>
</ul>
</nav>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment