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

Profile picture for user Phil Frilling
By Phil Frilling, 2 February, 2012
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:

function MYTHEME_preprocess_page(&$vars) {
  // Find the main menu with the active-trail in the key.
  $active = preg_grep("/active-trail/", array_keys($vars['main_menu']));

  // If the active-trail key was found.
  if(sizeof($active)) {
    // Get the returned key from the preg_grep() function earlier.
    $active_key = array_shift($active);
    // Create a new array with our active key and the same information as the primary links.
    $active_menu = array($active_key => $vars['main_menu'][$active_key]);
    // Combine our $active_menu array with the $secondary_menu.
    $vars['secondary_menu'] = array_merge($active_menu, $vars['secondary_menu']);
  }
}