0

I would like to create a sidebar in node.tpl.php that prints the parent menu items of the current page with a depth that follows the current page's depth by one level.

So if I have a menu structure like:

A
B
C
--C1
--C2
--C3
D

... and I am on page B, I would see in the sidebar:

A
B
C
D

... or if I am on page C2 I would see in the sidebar:

C1
C2
C3
0

Answering my own question:

In a custom module (or in your template.php):

1) Create a helper function:

// Helper function used to return the children of a specific menu item
function MODULENAME_menu_subtree_data($item, $tree) {
    foreach ($tree as $cid => $data) {
        if ($item['mlid'] == $data['link']['mlid']) {
            return array($cid => $data);
        }
        if ($data['below']) {
            $return = MODULENAME_menu_subtree_data($item, $data['below']);
            if ($return) {
                return $return;
            }
        }
    }
    return FALSE;
}

2) Create a reusable output function:

// Return all the menu items for the parent of the given page.
// $menuParent = menu_get_active_trail(); Needs to be called on the requesting page 
function MODULENAME_parent_menu($menuParent) {
    // Get active trail to current page
    $menuParent = menu_get_active_trail();
    // Pop off last item of trail as that is the current page
    $menuParentPop = array_pop($menuParent);
    // Store the new last item in the trail as this is the parent menu item
    $menuParent = end($menuParent);
    // Set the depth to which we want to return the parent menu tree
    $max_depth = $menuParent['depth'] +1;
    $mlid = $menuParent['mlid'];                
    $menu_item = menu_link_load($mlid);
    $tree = MODULENAME_menu_subtree_data($menu_item, menu_tree_all_data($menu_item['menu_name'], $link = NULL, $max_depth));
    $tree = array_shift($tree);
    $tree_array = menu_tree_output($tree['below']);
    return drupal_render($tree_array);
}

3) Place this code in your node.tpl.php file wherever you want the menu to be rendered:

<?php
// Print all the menu items for the parent of the current page.
print MODULENAME_parent_menu($menuParent = menu_get_active_trail());
?>

Notes: - Replace MODULENAME with your custom module name or theme name if in template.php - You can adjust the "depth" of what's returned by adjusting the $max_depth variable to suite your needs. 0 = show everything.

Totally welcome any way to improve this!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.