Get the subpages of a node in Drupal 7

 
 
 

Recently I have been doing a lot a Drupal 7 development for a new project, this project required quite a bit a custom programming to achieve the functionality that was needed.

One of these required the ability to pull out all of the menu items under a certain page or node. A lot of seasoned Drupal developers would choose a module called 'Views' to pull out the data as their first choice but I found that it didn't have the ability to query the menu tree, I also needed the content to be easily editable in the CMS (for the client to access) so the views module was not going to be an option.

In the end I created the below function that rebuilds a menu tree based on the given path (node) and menu, it can be added to the template.php file to be reused across the theme:


function getSubMenuPages($path = null, $selected_menu = null) {

     $parent = menu_link_get_preferred($path, $selected_menu);
     $parameters = array(
         'active_trail' => array($parent['plid']),
         'only_active_trail' => FALSE,
         'min_depth' => $parent['depth']+1,
         'max_depth' => $parent['depth']+5,
         'conditions' => array('plid' => $parent['mlid']),
     );

     return menu_build_tree($parent['menu_name'], $parameters);

}

Just pass the link path of the page you are querying, if you want to query the current page then just leave it as null and the function will default to the current page. You can also optional pass in the menu machine name that you want to check, this is helpful if the page (node) appears in more then one menu. The function will return an array of details about the subpages.