Skip to content

Instantly share code, notes, and snippets.

@besimhu
Last active August 29, 2015 14:17
Show Gist options
  • Save besimhu/28427788199c5b98c763 to your computer and use it in GitHub Desktop.
Save besimhu/28427788199c5b98c763 to your computer and use it in GitHub Desktop.
It takes the main navigation and if there are any submenu items corresponding with the page, it will generate the navigation.
<?php
function submenu($menu, $returnParent = false) {
global $post;
$menu_items = wp_get_nav_menu_items($menu);
$menu_childs = array();
$menu_IDs = array();
$parent_item = 0;
foreach ( $menu_items as $item ) {
$menu_childs[$item->menu_item_parent] = true;
$menu_IDs[$item->ID] = $item;
}
// get current top level menu item id
foreach ( $menu_items as $item ) {
if ( $item->object_id == $post->ID ) {
if(!isset($menu_childs[$item->ID] ) && $item->menu_item_parent==0 ){
return false;
}
$parent_item = ( isset($menu_childs[$item->ID] )) ? $item : $menu_IDs[$item->menu_item_parent];
break;
}
}
// display parent title
if($returnParent) {
echo '<h3>' . $parent_item->title . '</h3>';
}
// display the submenu
echo '<nav class="sub-menu-wrap">';
echo "<ul class="sub-menu>";
foreach ( $menu_items as $item ) {
if ( $item->menu_item_parent == $parent_item->ID ) {
$class = ( $item->object_id == $post->ID ) ? "class='current_page_item'" : "";
echo "<li {$class}><a href='{$item->url}' class='subnav' >{$item->title}</a></li>";
}
}
echo "</ul>";
echo "</nav>";
}
// To use
echo submenu('Menu Name');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment