Theme your Search Results

Drupal 6 preprocess functions and templates make a themers life a joy. Remember those ugly function overrides we had to do previously? All that's changed and pita tasks like adding vars to search results is now a 5 second job.

So how to theme your search results? Lets say we want to inject something below each result, could be Google adsense or your mothers recipe for home made pie—lets break it down.

1. Declare a variable in a preprocess function
2. Copy 'n' paste a tpl file
3. Print the variable in the template
4. Clear the cache

Wow, is that all? Yep.

## 1. Declare a variable in a preprocess function

Add to template_preprocess_search_result *(this goes in your theme's template.php file)*:

<?php
function mytheme_preprocess_search_result (&$vars) {
 
$vars['mums_recipe'] = t('Mums recipe for home-made pies is the best!');
}
?>

## 2. Copy 'n' paste a tpl file

Go to modules/search and copy the search-result.tpl.php file to your theme folder.

## 3. Print the variable in the template

<dt class="title">
  <a href="<?php print $url; ?>"><?php print $title; ?></a>
</dt>
<dd>
  <?php if ($snippet) : ?>
    <p class="search-snippet"><?php print $snippet; ?></p>
  <?php endif; ?>
  <?php if ($info) : ?>
    <p class="search-info"><?php print $info; ?></p>
  <?php endif; ?>

  // Print our new variable
  <?php if (!empty($mums_recipe)) : ?>
    <div class="mums-recipe"><?php print $mums_recipe; ?></div>
  <?php endif; ?>
</dd>

## 4. Clear the cache

Go to performance settings and clear cache data so Drupal picks up the new template.

That's it!

Last updated 14th April, 2009 - 3:03pm

Authored by Jeff Burnz on