Skip to content

Instantly share code, notes, and snippets.

@gormus
Created November 22, 2014 23:36
Show Gist options
  • Save gormus/ffdea909da5b0f35242a to your computer and use it in GitHub Desktop.
Save gormus/ffdea909da5b0f35242a to your computer and use it in GitHub Desktop.
How to get the menu tree in Drupal 7? Expanded or not.
<?php print $custom_main_menu; ?>
<?php
/**
* Gets the data structure representing a named menu tree.
*
* Since this can be the full tree including hidden items, the data returned
* may be used for generating an an admin interface or a select.
*
* @param $menu_name
* The named menu links to return
* @param $max_depth
* Optional maximum depth of links to retrieve. Typically useful if only one
* or two levels of a sub tree are needed in conjunction with a non-NULL
* $link, in which case $max_depth should be greater than $link['depth'].
* @param $attributes
* An associative array of key-value pairs to be converted to attributes of
* the menu wrapper.
*
* @return
* Returns HTML.
*/
function _MYTHEME_get_menu($menu_name, $max_depth = NULL, $attributes = array()) {
$menu_output = &drupal_static(__FUNCTION__, array());
if (!isset($menu_output[$menu_name])) {
$tree = menu_tree_page_data($menu_name, $max_depth);
$menu_output[$menu_name] = menu_tree_output($tree);
}
$attributes['role'][] = 'navigation';
$attributes['class'][] = 'p6-' . $menu_name;
return '<nav' . drupal_attributes($attributes) . '>' . render($menu_output[$menu_name]) . '</nav>';
}
/**
* Preprocess variables for page.tpl.php
*/
function MYTHEME_preprocess_page(&$vars) {
$is_front_page = drupal_is_front_page();
$main_menu_name = variable_get('menu_main_links_source', 'main-menu');
if ($is_front_page) {
$vars['custom_main_menu'] = _MYTHEME_get_menu($main_menu_name, 1);
}
else {
$vars['custom_main_menu'] = _MYTHEME_get_menu($main_menu_name, NULL);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment