Drupal 7 set active primary menu item first

Drupal 7 set active primary menu item first

For a customer project we had the requirements to set the active menu item (if selected) to first of all menu items dynamically.

This was quite tricky, because it was a little hard to find the right hook / theme hook to use. Finally we decided to use theme_preprocess_page within Adaptive Theme.

Here is our code snippet which may help you.

IMPORTANT NOTICE: If you don't use adaptive theme, you might not need to rebuild the $vars['primary_navigation'] but use another template menu variable instead!

  1. function MYTHEME_preprocess_page(&$vars) {
  2.   //#webksde: Set active menu item first!
  3.   if(!empty($vars['main_menu'])){
  4.     foreach($vars['main_menu'] as $menu_item_id => $menu_item_props){
  5.       // Set to first, if menu item is active (key contains "active-trail" string)
  6.       if(strpos($menu_item_id, 'active-trail')) {
  7.         $prepend = array($menu_item_id => $menu_item_props);
  8.         $vars['main_menu'] = array_merge($prepend, $vars['main_menu']);
  9.         break;
  10.       }
  11.     }
  12.     $vars['primary_navigation'] = theme('links', array(
  13.       'links' => $vars['main_menu'],
  14.       'attributes' => array(
  15.         'class' => array('menu', 'primary-menu', 'clearfix'),
  16.       ),
  17.       'heading' => array(
  18.         'text' => t('Main menu'),
  19.         'level' => 'h2',
  20.         'class' => array('element-invisible'),
  21.       )
  22.     ));
  23.   }
  24. }

Have fun using this snippet and leave a comment if it was helpful Smile