Skip to main content

Drupal Menu: Add Primary Menu Parent to the Beginning of the Secondary Menu

Today I needed to take the parent menu item from my primary links and add it to the beginning of my secondary menu links. To begin, my menu structure looks like this:

  • Primary 1
  • Primary 2
    • Secondary 2.1
    • Secondary 2.2
    • Secondary 2.3
  • Primary 3

Default Menu Setup

The $main_menu variable will print a list item with:

  • Primary 1
  • Primary 2
  • Primary 3

When you click on the 'Primary 2' link the $secondary_menu variable will display:

  • Secondary 2.1
  • Secondary 2.2
  • Secondary 2.3

What I Need

When a user clicks on the 'Primary 2' link, I wanted the $secondary_menu to display this:

  • Primary 2
  • Secondary 2.1
  • Secondary 2.2
  • Secondary 2.3

Solved

To accomplish this I used the template_preprocess_page() function to check the $main_menu for the active trail. Then I merged the active trail array item with the $secondary_menu variable. The code looks like this:

  1. function MYTHEME_preprocess_page(&$vars) {
  2.   // Find the main menu with the active-trail in the key.
  3.   $active = preg_grep("/active-trail/", array_keys($vars['main_menu']));
  4.  
  5.   // If the active-trail key was found.
  6.   if(sizeof($active)) {
  7.     // Get the returned key from the preg_grep() function earlier.
  8.     $active_key = array_shift($active);
  9.     // Create a new array with our active key and the same information as the primary links.
  10.     $active_menu = array($active_key => $vars['main_menu'][$active_key]);
  11.     // Combine our $active_menu array with the $secondary_menu.
  12.     $vars['secondary_menu'] = array_merge($active_menu, $vars['secondary_menu']);
  13.   }
  14. }


Comments