Drupal 7: How to add a custom CSS class to the last search result item on the search page

By Shivan Jaikaran, 14 November, 2012

This is a small tidbit of information in the event that you wanted to alter the Drupal search results page. You can add a custom CSS class to the last search result item (for whatever reason you may have). In my case, I wanted to remove the border-bottom from the last result, so I had to add a special CSS class to do this. Just follow these simple steps:

  1. Override template_preprocess_search_results Here is how to alter the code. This goes in your template.php: function yourthemename_preprocess_search_results(&$variables) { $variables['search_results'] = ''; if (!empty($variables['module'])) { $variables['module'] = check_plain($variables['module']); } //checking the total number of results $num_results = count($variables['results']); $counter = 0; foreach ($variables['results'] as $result) { $counter++; if ($num_results == $counter) { //means we have the last result so we add the class $variables['search_results'] .= theme('search_result', array('result' => $result, 'module' => $variables['module'], 'last' => 'last')); } else { $variables['search_results'] .= theme('search_result', array('result' => $result, 'module' => $variables['module'])); } } $variables['pager'] = theme('pager', array('tags' => NULL)); $variables['theme_hook_suggestions'][] = 'search_results__' . $variables['module']; }
  2. Now we override search-result.tpl.php Create this file and put it in your custom theme folder.
  3. "<?php print $attributes; ?>> <?php print render($title_prefix); ?>

    > "><?php print $title; ?>

    <?php print render($title_suffix); ?> <?php if ($snippet): ?>

    ><?php print $snippet; ?>

    <?php endif; ?> <?php if ($info): ?>

    <?php print $info; ?>

    <?php endif; ?>

  4. Clear your cache

Now if you search for something, you will notice that your very last search result has the CSS class of "last". This also works for search results that have a pager. That is, the last result on every page will have the class of "last".

Plain text

  • No HTML tags allowed.
  • Web page addresses and email addresses turn into links automatically.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Not specified