This gist is for showing an example of a custom wordpress menu.
-
-
Save mjot/06cba267144a9716caf79c4ad4f2dce6 to your computer and use it in GitHub Desktop.
Generate a custom structure for Wordpress menus.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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_; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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