Adding Sponsored results to Drupal's search results page

In many search engines, Google included, some results are put at the top as "sponsored links". These are put there by Google on behalf of companies that pay to have their links at the top. Google and other search ethically minded engines highlight those results in a different color and add a "Sponsored" title to those results, in order to differentiate them from normal results.

For a client's Drupal site, they wanted to do the same: add some sponsored links from a third party search site affiliated with the original site.

In order to do this, a proprietary file, external.inc with a function called external_search() was used to do all the heavy lifting of opening the URL of the external search engine, retrieve the results as XML, parse the XML results, and make out plain HTML out of them.

In order to integrate that with Drupal's search result page, the following function was added to template.php. The sponsored links were wrapped in divs so they can be themed with a different color.

A note on performance: this is a large and busy site. This external search added about 600 milliseconds to Drupal's search, which is already in the several hundreds of millseconds range. So be careful what impact this will have.

function phptemplate_search_page($results, $type) {
$enable_external = FALSE;
$external = path_to_theme() . '/external.inc';
if (file_exists($external)) {
include_once($external);
if (function_exists('external_search')) {
$enable_external = TRUE;
$key = arg(2);
// run the function to get results
$external_results = external_search($key);
list($ext_top, $ext_bottom, $ext_sidebar) = $external_results;
}
}
$output = '<dl class="search-results">';
if ($enable_external) {
$output .= '<div class="sponsored">' . $ext_top . '</div>';
}
foreach ($results as $entry) {
$output .= theme('search_item', $entry, $type);
}
if ($enable_external) {
$output .= '<div class="sponsored">' . $ext_bottom . '</div>';
}
$output .= '</dl>';
$output .= theme('pager', NULL, 10, 0);
return $output;
} 

Contents: 

Comments