Change Drupal 7 Menu List Class & Attributes — The Drupal Way!

Written by
Published
Updated
Typical Read
1 minutes

Have a few menus on your site & looking for a quick way to add or change the menu classes and attributes? Use the theme_menu_tree__[menu_name] override.

Have a few menus on your site & looking for a quick way to add or change the menu classes and attributes? Use the theme_menu_tree__[menu_name] override in your theme’s template.php file to change Drupal 7 menu list class and attributes:

// template.php
/**
* Override theme_menu_tree().
*/
function theme_menu_tree($variables) {
  return '<ul class="menu">' . $variables['tree'] . '</ul>';
}
/**
* Override theme_menu_tree__[menu_name]().
*/
function theme_menu_tree__main_menu($variables) {
  return '<ul class="menu">' . $variables['tree'] . '</ul>';
}

The code above will allow you to easily change all menu ul classes and other attributes or just the main menu’s ul classes and attributes.

Change Drupal 7 Menu List Class

Looking for a module to change Drupal 7 menu list class & attributes?

Unfortunately, I haven’t been able to find one that handles the individual menu ul instances cleanly, but the Menu Attributes module is a start. It gives users the ability to set the following attributes for each menu item — this does not help with setting the ul classes & attributes:

  • id
  • name
  • target
  • rel
  • class
  • style
  • accesskey

What about Drupal 8? Check this out article out by Tamas Hajas: Drupal 8 Twig: add custom CSS classes to menus (based on menu name).


Related Articles

1 comment on “Change Drupal 7 Menu List Class & Attributes — The Drupal Way!”.

# May 30, 2019

Thanks for the code template. Easy and helpful!

Join the conversation.

Your email address will not be published. Required fields are marked *

All comments posted on 'Change Drupal 7 Menu List Class & Attributes — The Drupal Way!' are held for moderation and only published when on topic and not rude. Get a gold star if you actually read & follow these rules.

You may write comments in Markdown. This is the best way to post any code, inline like `<div>this</div>` or multiline blocks within triple backtick fences (```) with double new lines before and after.

Want to tell me something privately, like pointing out a typo or stuff like that? Contact Me.