Adding an "active" class to menu links
This method works on all menus that are displayed as blocks i.e. not primary or secondary links. These sorts of menus are created using the theme_menu_tree() function. The process here is a bit more complicated than for primary links, but all you have to do is paste in the code below (I have done all the heavy lifting for you).
Put this in template.php somewhere:
<?php
/**
* Overrides for menu_tree to add first and last classes, as well as
* the menu id to each item.
*
* The first function redirects to the modified menu_tree function
* The second function uses the last function to theme the menu items
* The third function adds in menu ids to each menu item
*
* Taken from http://drupal.org/node/138656
*/
function phptemplate_menu_tree($pid = 1) {
if ($tree = phptemplate_menu_tree_improved($pid)) {
return "\n<ul class=\"menu\">\n". $tree ."\n</ul>\n";
}
}
function phptemplate_menu_tree_improved($pid = 1) {
$menu = menu_get_menu();
$output = '';
if (isset($menu['visible'][$pid]) && $menu['visible'][$pid]['children']) {
$num_children = count($menu['visible'][$pid]['children']);
for ($i=0; $i < $num_children; ++$i) {
$mid = $menu['visible'][$pid]['children'][$i];
$type = isset($menu['visible'][$mid]['type']) ? $menu['visible'][$mid]['type'] : NULL;
$children = isset($menu['visible'][$mid]['children']) ? $menu['visible'][$mid]['children'] : NULL;
$extraclass = $i == 0 ? 'first' : ($i == $num_children-1 ? 'last' : '');
$extraclass = $num_children == 1 ? 'single-item' : $extraclass; // if only one menu item, the class will be 'single-item'
$output .= theme('menu_item', $mid, menu_in_active_trail($mid) || ($type & MENU_EXPANDED) ? theme('menu_tree', $mid) : '', count($children) == 0, $extraclass);
}
}
return $output;
}
function phptemplate_menu_item($mid, $children = '', $leaf = TRUE, $extraclass = '') {
$extraclass .= menu_in_active_trail($mid) ? ($extraclass ? ' active' : 'active') : '';
return '<li class="'. ($leaf ? 'leaf' : ($children ? 'expanded' : 'collapsed')) . ($extraclass ? ' ' . $extraclass : '') . ' mid-' . str_replace('-', '', $mid) . '">'. menu_item_link($mid, TRUE, $extraclass) . $children ."</li>\n";
}
?>
