0

I want to add a class to a menu - doing it in hook_menu won't work because I'm adding an icon with the icon API, and this seems to override any classes put on the menu items.

I have this preprocess function:

/**
 * hook_preprocess_page().
 */
function MYMODULE_preprocess_page(&$vars) {
  $vars['main_menu']['menu-1914']['attributes']['class'] = array('message');
}

But it doesn't seem to add the css class "message" onto my element.

How do I reliably add a css class to a menu item before display, but before icon API would display it. Theming has to be my weakest Drupal skill.

3
  • 1
    You may try drupal.org/project/menu_attributes module
    – Andrew
    Jul 14, 2015 at 6:05
  • Have you tried $vars['main_menu']['menu-1914']['attributes']['class'][] = 'message'; ? You need to add another element to the array, not to override it.
    – rreiss
    Jul 14, 2015 at 10:14
  • No, I want the class to be added programmatically with conditions, so menu_attributes will not work.
    – Jack Ryan
    Jul 14, 2015 at 11:56

2 Answers 2

1

To add class in navigation's <ul> element, include below code in template.php

function THEMENAME_menu_tree__menu_MENUNAME($variables) {
return '<ul class="CLASSNAME YOU WANT TO ADD">' . $variables['tree'] . '</ul>';
}
0

I was able to apply a class to the menu item this way:

function MYMODULE_preprocess_menu_link(&$variables) {
  if($variables['element']['#original_link']['link_title'] == "Messages") {
  $variables['element']['#attributes']['class'][] = "no-message";
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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