How to Add unique classes to Drupal menus

Sometimes you want to be able to style menu items individually. For example you may want to use image replacement to display icons instead of the text, or you may want to make one menu item stand out from the rest.

Drupals Primary and Secondary links allow you to do this because they print a class on the li that includes the mlid, so its easy to target a particular link doing something like:

li.menu-123 a {font-weight: bold;}

But, in normal Drupal menus, the ones that appear in blocks, no such classes appear, which leaves them all with the same style.

There is a very good module for getting around this called Menu Attributes, which allows you to specify additional attributes for menu items such as id, name, class, style, and rel. The problem here is that you need an additional module, and if like us, you're building themes for clients sites you don't really want to rely on 3rd party modules to be installed and maintained, not for trivial design aspects such as few classes on menu items in any case.

The solution is to override theme_menu_item_link, and add the mlid to the actual link.

Drop this snippet into your template.php file and as per usual, replace themeName with your themes name.

<?php
function themeName_menu_item_link($link) {
  if (empty(
$link['localized_options'])) {
   
$link['localized_options'] = array();
  }
  if (empty(
$link['localized_options']['attributes']['class'])) {
   
$link['localized_options']['attributes']['class'] = 'menu-'. $link['mlid'];
  }
  else {
   
$link['localized_options']['attributes']['class'] .= ' menu-'. $link['mlid'];
  }
  return
l($link['title'], $link['href'], $link['localized_options']);
}
?>

Last updated 26th August, 2009 - 3:42am

Authored by Jeff Burnz on