[Drupal] How to display 'Main menu' with sub links in Drupal 7?

By | 20th Jul 2015 | 2 min read

We were on a venture to convert all our Drupal 7 themes to their responsive versions and we got stuck in between. The issue was with the main menu that it was not displaying sub links. We have gone through the code carefully and we found that only the top level menu items are being set to the main menu variable. To render all menu items from main menu, we should have defined it in theme's template.php file.

We had our menu code somewhat like this,

<?php
  print theme('links__system_main_menu', array(
      'links'       => $main_menu,
      'heading'     => null,
      'attributes'  => array(
          'class'   => array('nav navbar-nav'),
      ),
  ));
?>

It only displayed the top level menu items whereas we wanted to achieve this:

<ul>
    <li>
        Top Level
        <ul>
            <li>Sub Level</li>
        </ul>
    </li>
</ul>

So, here is what we did:

Step 1: Get the menu tree

Get the complete menu tree and set as a page variable. For this, add the following code in your template.php file.

<?php
  function your_theme_preprocess_page(&$vars) {
    // To display sublinks.
    $main_menu_tree = menu_tree(variable_get('menu_main_links_source', 'main-menu'));
    $vars['main_menu'] =  $main_menu_tree;
  }
?>

Step 2: Add necessary CSS classes

Now, add the necessary CSS classes for theming. This can also be included in the template.php file.

<?php
function your_theme_menu_tree__main_menu(&$vars) {
  // To add CSS class to the main menu ul
  return '<ul class="nav navbar-nav">' . $vars['tree'] . '</ul>';
}
?>

Step 3: Print the complete main menu

Finally, print the main menu in our page.tpl.php file.

<?php
  print render($main_menu);
?>

Please note that, if you have a custom front page - page--front.tpl.php, you should print the menu in that too.

Don't forget the clear the cache!!! You're done.