Add first and last classes to secondary local tasks

We had a project recently where we needed to add first and last classes to Drupals secondary local tasks. I was in a bit of a hurry so instead of trying to figure this out myself I Googled it and pretty quickly found this post on Drupal.org which seemed to fit the bill. Problem is the post doesn't actually tell you how or where to use the snippet, which isn't much good for those of you struggling with Drupal in the first place. Never fear, I'll show you how to get those handy first/last classes into Drupals secondary local tasks.

The secret not revealed in that post is to override theme_menu_local_tasks() and use the code to affect only the secondary tasks.

As always replace themeName with your themes name. This function override goes in your themes template.php file. You may need to clear your sites cache to get it kick in.

<?php
function themeName_menu_local_tasks() {
 
$output = '';
  if (
$primary = menu_primary_local_tasks()) {
   
$output .= "<ul class="tabs primary">\n". $primary ."</ul>\n";
  }
  if (
$secondary = menu_secondary_local_tasks()) {
   
// split into an array
   
$items = (explode("/li>\n<", menu_secondary_local_tasks()));
   
// process the first item
   
if(strpos($items[0], 'li class=') !== FALSE) {
     
$items[0] = str_replace('li class="', 'li class="first ', $items[0]);
    }
    else {
     
$items[0] = str_replace('li', 'li class="first"', $items[0]);
    }
   
// process the last item
   
$lastindex = count($items) - 1;
    if(
strpos($items[$lastindex], 'li class=') !== FALSE) {
     
$items[$lastindex] = str_replace('li class="', 'li class="last ', $items[$lastindex]);
    }
    else {
     
$items[$lastindex] = str_replace('li', 'li class="last"', $items[$lastindex]);
    }
   
// create a string from the array
   
$secondary = implode("/li>\n<", $items);
   
// Output the secondary links with new first and last classes
   
$output .= "<ul class="tabs secondary">\n". $secondary ."</ul>\n";
  }
  return
$output;
}
?>

Note: in the post on Drupal.org that features very similar code to this be aware there is also a hackish attempt to get something similar working in preprocess_page, which is pretty ugly and doesn't actually work...

Last updated 27th December, 2009 - 2:48pm

Authored by Jeff Burnz on