Tag Archives: Useful Code

WordPress Search page ‘Showing x of y results’

I wrote this handy snippet of code for a WordPress theme recently (I say recently, on checking the date of my first post, it was a year ago), I’ve shared it on the WordPress forums if anyone wants it. It works with a paged search page to just display a total number of results, in the format of ‘Showing 1-15 of 759‘.

Someone might find use for it, or perhaps can expand on it. I threw this into my search.php in my theme but alternatively it could be wrapped in a function and included in your functions.php file.


<?php
 /* Search Total Count */
 $allsearch = &new WP_Query("s=$s&showposts=-1");
 $count = $allsearch->post_count;
 wp_reset_query();

 /* Number of posts per page and page number */
 $num_of_posts = 15;
 $pageNumber = (get_query_var('paged')) ? get_query_var('paged') : 1;

 /* Showing the lower post value */
 $n = ($pageNumber-1)*$num_of_posts;
 $n = $n+1;

 /* Showing the higher/highest post value */
 $m = $pageNumber * $num_of_posts;
 if($m > $count){
 // if m is bigger than the count var, it sets the
 // highest value equal to the count, this is for the last page of results
 $m = $count;
 }
?>

To display the results, it’s just a matter of choosing how you want to format it. For my particular example, I did it this way.

<?php
if($count > 0){
echo '
      Showing <strong>'.$n.'</strong>
      -<strong>'.$m.'</strong>
      of <strong>'.$count.'</strong>';
}
else{
     echo '<strong>No Results</strong>';
} ?>

I hope to include more little nuggets of code in the future. I’ve picked up so many from different blogs, and I’ve helped out on the WordPress forums many-a-time writing custom little functions to help people out of binds. So it will hopefully be of some benefit to someone in the future.

Posted in Technology | Tagged as , , | Comments Off
Top
close

Sorry, your browser is out of date!

My website has been designed with modern browsers in mind with adequate fallback for most browsers, we no longer support IE6, and the website is functional in IE7+. We would recommend that you upgrade your out of date browser to the latest version of the below browsers.