Adding active trail classes to your menu links in Drupal 7

So I’m working on a site with a gallery page with /art as a path, along with single artworks pages with the path art/[title]. When on a single artwork page, I still wanted the visual indicator that the user was in the main “art” section of the website, ideally by highlighting the /art links in menus. I found a module, Menu Trail By Path, which took care of this.

However, I also had another section for photography. This was a separate gallery, living at art/photography, with single photos living at art/gallery/[photo title]. I wanted to highlight both the top level /art menu item as well as the art/photography menu item, but Menu Trail By Path didn’t want to go that deep.

So I wrote a chunk of code for when you want to indicate on all of your menu links when a menu item’s path is part of the URL for your current path. I was able to remove the Menu Trail module, and this (which lives in template.php in your theme) took care of everything:

function yourtheme_menu_link($variables) {
  //get path alias of current page
  $current_path = drupal_get_path_alias();
  //get path alias of menu item
  $menu_path = drupal_get_path_alias($variables['element']['#href']);
  //if the href of the menu item is found in the current path
  if (strstr($current_path, $menu_path)){
    //add active-trail class to li and a tags for that item
    $variables['element']['#attributes']['class'][] = 'active-trail';
    $variables['element']['#localized_options']['attributes']['class'][] = 'active-trail';
  return theme_menu_link($variables);

Leave a Reply