I’ve had to develop a couple of Drupal sites recently where I needed to grab the array of Primary Links and do something bespoke with it. Drupal provides functions for this, but they return so much data it can be difficult to work with it, particularly when you have large menus.

The $primary_links variable returns a huge amount of data yet doesn’t include the children of menu items, even if the “expanded” property is set to true.

The function menu_primary_links() provides the right level of data - the title and link, but also doesn’t include a menu item’s children.

The way to get the full primary links data is to call the function: menu_tree_page_data(‘primary-links’). This returns all required data, but again contains a lot of other unnecessary data.

So I wrote this little recursive function to clean the array so it only contains the data I need:


function clean_navigation($links) {

    $result = array();
    foreach($links as $id => $item) {

        $new_item = array('title' => $item['link']['title'], 'link_path' => $item['link']['link_path'], 'href' => $item['link']['href']);

        if ($item['below']) {
            $new_item['below'] = clean_navigation($item['below']);
        }
        $result[] = $new_item;
    }
    return $result;
}

The above function can sit in your template.php file, and can be called from anywhere. I put the following line in my page.tpl.php:


$nav = clean_navigation(menu_tree_page_data('primary-links'));

So finally the $nav variable contains a nice simple array containing only the required information:


[0]=>
array(3) {
    ["title"]=>
    string(4) "Home"
    ["link_path"]=>
    string(7) "<front>"
    ["href"]=>
    string(7) "<front>"
}
[1]=>
array(4) {
    ["title"]=>
    string(7) "Finance"
    ["link_path"]=>
    string(7) "node/11"
    ["href"]=>
    string(7) "node/11"
    ["below"]=>
    array(1) {
        [0]=>
        array(3) {
            ["title"]=>
            string(6) "Events"
            ["link_path"]=>
            string(14) "finance/events"
            ["href"]=>
            string(14) "finance/events"
        }
    }
}
and so on...
« Back