Better Search Results Counts in WordPress

Posted: December 31, 2013 Comments

I recently stumbled on the following snippet of code in your average WordPress theme:

<?php if ( is_home() ) : ?>
<h2><?php echo the_title(); ?></h2>
<?php elseif ( is_search() ): ?>
<h1><?php
$search_count = 0;
$search = new WP_Query("s=$s&showposts=-1");
if($search->have_posts()) {
while($search->have_posts()) {
$search->the_post();
$search_count++;
}
}
echo $search_count;
?> <?php _e('Search results'); ?></h1>
<?php endif; ?>
view raw gistfile1.php hosted with ❤ by GitHub

It’s truncated, but the basic job of this file was to check to see which page we were on, and output a proper heading on the page. At first glance it might seem harmless, but if you take a look at the part getting executed on search pages you might notice there is some room for improvement.

When is_search() is true the code spins up a new WP_Query, passing along the search query and disabling pagination. From there it loops through the results and increments a variable, effectively determining how many total posts were returned from the search. It gets the job done, but there’s extra overhead we don’t need in the form of an additional query in addition to looping through (what could be) a ton of Post objects.

This implementation can be improved by instead relying on some work WordPress already did for us. Every time WP_Query does it’s job, it sets a number of properties that are often useful elsewhere. In this case we’ll pay particular attention to $wp_query->found_posts, which does exactly what’s on the tin: stores how many total posts were found for that query. The above snippet can be reduced to:

<?php if ( is_home() ) : ?>
<h2><?php echo the_title(); ?></h2>
<?php elseif ( is_search() ): ?>
<h1><?php echo $wp_query->found_posts; ?> <?php _e('Search results'); ?></h1>
<?php endif; ?>
view raw gistfile1.php hosted with ❤ by GitHub

Which saves both a database call in addition to the overhead of looping through any number of post objects.

Get my newsletter

Receive periodic updates right in the mail!

  • This field is for validation purposes and should be left unchanged.

Leave a Reply

Your email address will not be published. Required fields are marked *