4

I'm trying to theme my menu to alter the default UL classes. So far I'm working with the following function:

function theme_menu_tree($variables){
  return '<ul class="my-class">' . $variables['tree'] . '</ul>';
}

This works great but I need to apply a different class to the UL inside a parent item. Right now I get

<ul class="my-class">
  <li class="dropdown">Item
    <ul class="my-class">
      <li>Link1</li>
      <li>Link2</li>
    </ul>
  </li>
</ul>

How can I target the second UL to give it a different class using the theme_menu_tree function?

11

This kind of issues should be managed by CSS, but if you realy need to override the theme_menu_tree() and define a custom ul class there, you can do that with the help of custom global variable created in theme_menu_link().

Not sure if it's "the right way" to do that, but works:

/**
 * Implements theme_menu_tree__[MENU NAME].
 */
function YOURTHEME_menu_tree__[MENU NAME]($variables) {
  global $level;
  $class = ($level == 1) ? 'my-class' : 'my-class-for-depth-' . $level;
  return '<ul class="'.$class.'">' . $variables['tree'] . '</ul>';
}

/**
 * Implements theme_menu_link__[MENU NAME].
 */
function YOURTHEME_menu_link__[MENU NAME]($variables) {

  $element = $variables['element'];
  $sub_menu = '';   

  // set the global variable in order to use it in hook_menu_tree()
  // I called it "level" to avoid confusing with the $depth
  global $level;

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
    $level = 1; // set the level as first for each list with submenu
  }
  else {
    $level = $element['#original_link']['depth'];
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}
  • 1
    Unfortunately that does not work. Both ULs were given the 'another-ul-class' in your example. – Brad Chesterfield Jul 2 '13 at 22:29
  • hm.. it have to work. Clear cache please, and use your theme name instead 'theme' – Jack-PL Jul 2 '13 at 22:32
  • There was a small bug in the code. I fixed that. – Jack-PL Jul 2 '13 at 22:49
  • 1
    I'm actually having an issue with the code. Could you take a look at this secondary post I made? drupal.stackexchange.com/questions/81563/… – Brad Chesterfield Aug 15 '13 at 1:07
  • 1
    I was looking for this for days. You sir are a hero..haha ;) – James Cazzetta Jan 7 '15 at 22:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.