Created
March 20, 2015 16:41
-
-
Save phpdave/8636a8c1a1983813fa4a to your computer and use it in GitHub Desktop.
WordPress: Get current level navigation menu items and their children 1 level deep
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
<?php | |
//Get the Page Id of the parent | |
if ($post->post_parent) | |
{ | |
//There's a parent post lets get the ancestors and grab the top | |
$ancestors = get_post_ancestors($post->ID); | |
$parentPostId = $ancestors[count($ancestors) - 1]; | |
} | |
else | |
{ | |
//this page is the top most menu item | |
$parentPostId = $post->ID; | |
} | |
$parentNavMenuId=0; | |
$menu_name = 'primary'; | |
if (( $locations = get_nav_menu_locations() ) && isset($locations[$menu_name])) | |
{ | |
$menu = wp_get_nav_menu_object($locations[$menu_name]); | |
$menu_items = wp_get_nav_menu_items($menu->term_id); | |
$menu_list = '<ul class="left-menu-' . $menu_name . '">'; | |
//Find parent menu id by the post id | |
foreach ((array) $menu_items as $key => $menu_item) | |
{ | |
if ($menu_item->object_id == $parentPostId) | |
{ | |
$parentNavMenuIds[] = $menu_item->ID; | |
} | |
} | |
foreach ((array) $menu_items as $key => $menu_item) | |
{ | |
if (in_array($menu_item->menu_item_parent,$parentNavMenuIds)) | |
{ | |
$title = $menu_item->title; | |
$url = $menu_item->url; | |
$menu_list .= '<li><a href="' . $url . '">' . $title . '</a></li>'; | |
//Echo out children | |
$childitems=""; | |
foreach ((array) $menu_items as $key_possible_child => $menu_item_possible_child) | |
{ | |
//Check if there's any children for this item | |
if($menu_item_possible_child->menu_item_parent==$menu_item->ID) | |
{ | |
//Found one lets add it | |
$title = $menu_item_possible_child->title; | |
$url = $menu_item_possible_child->url; | |
$childitems .= '<li><a href="' . $url . '">' . $title . '</a></li>'; | |
} | |
} | |
if($childitems!="") | |
{ | |
//if this is not blank we found a child(ren) and should wrap it in a ul | |
$menu_list .= '<ul>'.$childitems. '</ul>'; | |
} | |
} | |
} | |
$menu_list .= '</ul>'; | |
} | |
else | |
{ | |
$menu_list = '<ul><li>Menu "' . $menu_name . '" not defined.</li></ul>'; | |
} | |
echo $menu_list; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment