It’s a common design pattern for search engines to display the total number of search results found. Surprisingly most WordPress themes don’t do this, and it’s incredibly easy. There are a few methods out there, but I’ve found that this is the most efficient and effective way.
/**
* A title for the search.php template that displays the total number of search results and search terms
*/
function search_results_title() {
if( is_search() ) {
global $wp_query;
if( $wp_query->post_count == 1 ) {
$result_title .= '1 search result found';
} else {
$result_title .= $wp_query->found_posts . ' search results found';
}
$result_title .= " for <strong class='search-terms'>“" . wp_specialchars($wp_query->query_vars['s'], 1) . "”</strong>";
echo $result_title;
}
}
This function will output allow you to use a new template tag in your theme called search_results_title(). The template will output the following HTML:
4 search results found for <strong class='search-terms'>“lorem”</strong>
Replace the main title (usually an H1) on your search.php template with the following bit of code:
if( function_exists('search_results_title') ): ?>
<h1 class="section-title"><?php search_results_title(); ?></h1>
<?php else: ?>
<h1 class="section-title">Search Results Found</h1>
<?php endif;
That’s it, you now have a better user experience on your WordPress search results page! If you’d like to take your WordPress site search to the next level I suggest checking out Yoast’s helpful post on making the WordPress search suck less.