Site icon WP Smith

How to Get All the Children of a Specific Nav Menu Item

***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]