user3613095
user3613095

Reputation: 99

Drupal 7: programmatically get main menu with sub-menus

I want to display my main menu links with sub-menu links with an individual class and id.

This works for the 1st level links but unfortunately doesnt show second level links as the $main_menu value doesnt contain them:

                <?php print theme('links', array(
                    'links' => $main_menu,
                    'attributes' => array(
                        'id' => 'mobile-menu-links',
                        'class' => array('links', 'clearfix'),
                    ),
                )); ?>

Any Idea?

Upvotes: 0

Views: 4269

Answers (1)

skarist
skarist

Reputation: 1030

You can get the main menu with sub menus and manipulate it like this:

    $main_menu_tree = menu_tree('main-menu');
    foreach ($main_menu_tree as $key => &$main_menu_item) {
        if (is_numeric($key)) {
            $main_menu_item['#below']['#theme_wrappers'][0] = 'some_other_theme_wrapper';
        }
    }
    print drupal_render($main_menu_tree);

Here the default theme wrapper (menu_tree__main_menu) is replaced with some_other_theme_wrapper, something that would need to be implemented.

You should find a number of posts on drupal stackexchange discussing this. Here is just one:

https://drupal.stackexchange.com/questions/35066/i-want-to-customze-menu-tree-output

You can also render main menu and sub menu separately like this:

        <div class="menu"> 
            <?php print theme('links__system_main_menu', array(
              'links' => $main_menu,
              'attributes' => array(
                'id' => 'main-menu-links',
              ),
              'heading' => array(
                'text' => t('Main menu'),
                'level' => 'h2',
                'class' => array('element-invisible'),
              ),
            )); ?>          
        </div>
        <?php endif;?>
        <?php if ($secondary_menu): ?>
        <div class="submenu">
            <?php print theme('links__system_secondary_menu', array(
              'links' => $secondary_menu,
              'attributes' => array(
                'id' => 'secondary-menu-links',
              ),
              'heading' => array(
                'text' => t('Sub menu'),
                'level' => 'h2',
                'class' => array('element-invisible'),
              ),
            ))
        </div>

Upvotes: 1

Related Questions