Error message

Deprecated function: implode(): Passing glue string after array is deprecated. Swap the parameters in drupal_get_feeds() (line 394 of /home1/tylerfra/public_html/includes/common.inc).

Drupal How to Add a CSS ID or Class Name to a Menu Item Link

Category: 

Do you need to add a unique CSS ID or Class Name to a Drupal menu item link? Then you've come to the right place. Check out this example below...

Menu item link before:

<a href="/my_node_url_path">My Node</a>

Menu item link after:

<a href="/my_node_url_path" id="my_css_id" class="my_css_class">My Node</a>

How to do it...

Implement theme_menu_item_link() in your theme's template.php file, like so:

/**
 * Implements theme_menu_item_link().
 */
function my_theme_menu_item_link($link) {
  if (empty($link['localized_options'])) {
    $link['localized_options'] = array();
  }
  
  // Add a unique id and css class name to my node's menu item link.
  // Add whitespace around the class name so it doesn't collide with any other
  // css class names.
  if ($link['link_path'] == 'my_node_url_path') {
    $link['localized_options']['attributes']['id'] = 'my_css_id';
    $link['localized_options']['attributes']['class'] .= ' my_css_class ';

    // Trim css class whitespace.
    $trim = trim($link['localized_options']['attributes']['class']);
    $link['localized_options']['attributes']['class'] = $trim;
  }

  return l($link['title'], $link['href'], $link['localized_options']);
}

That's it! Now go forth and add some custom CSS IDs and Class Names to your Drupal menu item links, or else.

Caveats

You may have to use the system path to your menu item link instead of a custom url alias in the boolean, depending on how you setup the menu item link, for example:

if ($link['link_path'] == 'node/123') { ... }

Comments

Hi,

I also tried the menu_attributes module, it worked well for me:
http://drupal.org/project/menu_attributes

The allows you to set IDs, CSS classes, and other stuff, without programming.

tyler's picture

Hi Francis, thank you for sharing! I've seen this module a few times but haven't had a chance to check it out. I've heard good things about it though. Looks like it is much easier than writing code to accomplish this!