WordPress search result count

This is a little feature I really want to have on my blog. While not many people will use the search bar on a normal web site, it’s definitely worth providing a better experience for those who actually use.

The method

The easiest way to do this (and I think it’s the proper way) is to pull the information retained in $wp_query object about the search query.

Simply put, after a user has performed a search on your site, wordpress will then do its magic to determine what query it’s dealing with (search query in this case) and dispay the requested posts. Fortunately, wordpress retains lots of useful information about the request, including the number of posts returned, which can be pulled on demand.

The easy way

To display the figure, just output the $wp_query->found_posts which stores the needed value. For example, putting <?php echo $wp_query->found_posts; ?> in search.php will display the number of posts returned in the performed search. Here is the code in my search.php with some additional conditional statements to make it more flexible

  $resultnumber = $wp_query->found_posts;
  if ($resultnumber == 1) $displaytext = "only one result";
  elseif ($resultnumber == 0) $displaytext = "no results";
  else $displaytext = "$resultnumber results";
<p>Your search <?php the_search_query(); ?>
returned <?php echo $displaytext; ?></p>

<?php the_search_query(); ?> is used to display the search term. The conditional statement will help us avoid grammar mistakes such as displaying “there is 1 posts” and provide a more helpful message for the users.

The other ways

Other methods I found and tried

  • Rerunning the same search query and counting the posts again. This is quite unnecessary and over-complicated. You can find the method here
  • Incrementing a variable inside the loop to count the search results. Then display the counted number outside the loop

More than just search

As mentioned above, since $wp_query->found_posts; stores the number of posts found in a query, it can be used in other templates as well. So, to display the the number of posts filed in a category, tag, posted in a specific year… just put the code in the archive.php, category.php, tag.php… or other needed templates.