I am having the below code to load the main menu tree.

$tree = menu_tree_all_data('main-menu');
  $parentMenu = array();
  $index = 0;
  foreach($tree as $key => $value) {
    if (!empty($value['link']['hidden'])) {
    $submenu = array();
    foreach($value['below'] as $subMenu) {
      if (!empty($subMenu['link']['hidden'])) {
      $tid = explode('/', $subMenu['link']['link_path']);
      $submenu[]= array(
        'link_title' => $subMenu['link']['link_title'],
        'link_path' => drupal_get_path_alias($subMenu['link']['link_path']),
        'link_tid' => $tid,
    $parentMenu[$index]['link_title'] = $value['link']['link_title'];
    $parentMenu[$index]['link_path'] = drupal_get_path_alias($value['link']['link_path']);
    $tidSubmenus = explode('/', $value['link']['link_path']);
    $parentMenu[$index]['link_tid'] = $tidSubmenus[2];
    $parentMenu[$index]['sub_menu'] = $submenu;

  $vars['parentMenu'] = $parentMenu;

Here, into the variable, $parentMenu I am storing the main menu tree. After that i am printing the menu structure using below code in template.

 <?php if ($parentMenu): ?>
   //printing the html structure
   <?php foreach($parentMenu as $mainMenu) { ?>
     //printing the html structure
     <?php foreach($mainMenu['sub_menu'] as $k => $childMenu) { ?>
        <?php print $childMenu['link_title']; ?> 
              //printing the html structure
               $recent_content = views_embed_view('masala_taxonomy_section','block_10', $childMenu['link_tid'][2]);
                print $recent_content;
<?php } ?>
<?php } ?>

This is taking too long to store the home page and other page... am I missing anything here... or is there need to optimize the code?

  • 1
    Have you got quite a big menu structure? I see you're only displaying the first 2 levels aren't you? With menu_tree_all_data you're loading the full menu structure so if its a large menu that will be a slow call in itself. You can pass a 2nd parameter to that function with the depth .e.g $tree = menu_tree_all_data('main-menu',2);
    – Leigh
    Dec 19 '19 at 9:13
  • For caching it, cache_set/cache_get on your array. Also, only grab the menu you need, as Leigh said.
    – Kevin
    Dec 19 '19 at 14:19

Your Answer

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

Browse other questions tagged or ask your own question.