***UPDATED (12/6/2011): I have just updated this function to allow for basic depth (all or none).
Recently, I needed to get all the children (along with the parent) of a particular nav menu item. Since pages can do this very well, I looked into the function get_page_children(). So I modified that function to create get_nav_menu_item_children(). I have recommended this to WordPress core (ticket). What are your thoughts?
[php]
/**
* Returns all child nav_menu_items under a specific parent
*
* @param int the parent nav_menu_item ID
* @param array nav_menu_items
* @param bool gives all children or direct children only
* @return array returns filtered array of nav_menu_items
*/
function get_nav_menu_item_children( $parent_id, $nav_menu_items, $depth = true ) {
$nav_menu_item_list = array();
foreach ( (array) $nav_menu_items as $nav_menu_item ) {
if ( $nav_menu_item->menu_item_parent == $parent_id ) {
$nav_menu_item_list[] = $nav_menu_item;
if ( $depth ) {
if ( $children = get_nav_menu_item_children( $nav_menu_item->ID, $nav_menu_items ) )
$nav_menu_item_list = array_merge( $nav_menu_item_list, $children );
}
}
}
return $nav_menu_item_list;
}
[/php]
chodorowicz says
That would be very useful. I’ve been needing it lately and finally used Gecka Submenu plugin (but having it inbuilt or just as a function in functions.php would be much better).
I don’t get the second parameter ‘nav_menu_items’ – could you elaborate on it a bit…
Travis Smith says
Hello,
It can be populated by
nav_menu_items = wp_get_nav_menu_items( $menu_id, array( 'post_status' => 'publish,draft' ) );
Thanks,
Travis
Rafael Ehlers says
I think your code, is similar to this: http://www.viper007bond.com/wordpress-plugins/add-descendants-as-submenu-items/
manoj says
Thanks Dude
Kurt says
This sounds like something I have been searching for. Everything I find is always based on post hierarchy instead of menu hierarchy. Could you give me some additional direction on how to implement this. I am fairly new to WordPress. How do I use this. Where do I put this code?
Thank You!
Nancy says
Huzzah! Easy fix for a cumbersome problem. Thanks for sharing your efforts!
Vishal Kakadiya says
Thank you so much man, this code save my lots of time.
Nils Harder says
Nice Idea, But I cannot make it work. $nav_menu_item_list is empty.
Didou Schol says
Excellent, this worked like a charm! Thanks for putting it out there, it helped me a lot.