December 22nd, 2011
Snippets
In my ever increasing quest to make a more user friendly Drupal environment for my clients. I have been trying to figure out how to add a unique class to menu items. Recently I came across this snippet on drupal.org.
In order to use this snippet, you must place this code in your theme's template.php file.
<?php
function phptemplate_menu_item($link, $has_children, $menu = '', $in_active_trail = FALSE, $extra_class = NULL) {
$class = ($menu ? 'expanded' : ($has_children ? 'collapsed' : 'leaf'));
if (!empty($extra_class)) {
$class .= ' '. $extra_class;
}
if ($in_active_trail) {
$class .= ' active-trail';
}
if (!empty(
$link)) {
// remove all HTML tags and make everything lowercase
$css_id = strtolower(strip_tags($link));
// remove colons and anything past colons
if (strpos($css_id, ':')) $css_id = substr ($css_id, 0, strpos($css_id, ':'));
// Preserve alphanumerics, everything else goes away
$pattern = '/[^a-z]+/ ';
$css_id = preg_replace($pattern, '', $css_id);
$class .= ' '. $css_id;
}
return '<li class="'. $class .'">'. $link . $menu ."</li>\n";
}
?>This code will add a class based on the link's title. The only problem I see with this method is that if you use the class and then change the name of the link, it will also change the name of the class, so keep that in mind when using this snippet. Other than that, I will be adding this to my snippet library.

