Add a total number of results to ApacheSolr result pages

By default the Drupal ApacheSolr module does not display the total number of results for a given search. This is how to add it.

For my use it makes sense to add the result total to the Search form using hook_form_[form_id]_alter().

/**
 * Implementation of hook_form_[form_id]_alter().
 */
function ms_solr_site_form_search_form_alter(&$form, &$form_state) {
  if ($form['module']['#value'] == 'apachesolr_search') { //Will change all searches otherwise.
    if (apachesolr_has_searched() && ($response = apachesolr_static_response_cache())) {
      $query = apachesolr_current_query();
      $keywords = $query->get_query_basic();
      $num_found = $response->response->numFound;
      
      $form['num_found'] = array(
        '#prefix' => '<div class="number-found">',
        '#suffix' => '</div>',
        '#value' => t('There are @number results for "@keywords"', array(
          '@number' => $num_found,
          '@keywords' => $keywords)
        ),
        '#weight' => -1,
      );
    }
  }
}

Comments

Perfect! Thanks for the snippet. I chucked it in to a block instead.

Another approach might be to add the following code to search-results.tpl.php in your theme directory:

global $pager_page_array, $pager_total_items;
$count = variable_get('apachesolr_rows', 10);
$start = $pager_page_array[0] * $count + 1;
print t('Showing %start to %end of %total results found.', 
  array(
    '%start' => $start,
    '%end' => $start + $count - 1,
    '%total' => $pager_total_items[0]
  )
);

This will print "Showing 21 to 30 of 6464 results found." on your search results page.

Thank you for your example.
But when you have let's say 25 results, then the message says:
"Showing 20 to 30 of 25 results found."

Shouldn't it be saying
"Showing 20 to 25 of 25 results found."?

Yes, in that case some additional code is required to check the total count.

Use this:

global $pager_page_array, $pager_total_items;
$count = variable_get('apachesolr_rows', 10);
$start = $pager_page_array[0] * $count + 1;
$end = $start + $count - 1;

if($pager_total_items[0] < $end) {
  $end = $pager_total_items[0];
}

print t('Showing %start to %end of %total results found.',
  array(
    '%start' => $start,
    '%end' => $end,
     '%total' => $pager_total_items[0]
  )
);