In prepping the new site design for theandystratton.com, I wanted to show the total number of search results on my search page.
I started by displaying a count($posts), but since I’ve got my installation showing 5 posts per page, that consistently displayed 5 or less posts. Less than desirable.
So, the next step was duplicating the search query so I could get the count, and as usual I like to try to use the WordPress functions as opposed to touching the database directly:
<?php
$tmp_search = new WP_Query('s=' . wp_specialchars($_GET['s']) . '&show_posts=-1');
$count = $tmp_search->post_count;
echo $count . ' results for ' . htmlentities($_GET['s']) . '.';
?>
Unfortunately, the code above still gave me the wrong count. Why? My settings were still set to 5 posts per page; and the WP Query object as assuming this constraint.
The Solution: send posts_per_page=-1 as part of the query.
<?php
$tmp_search = new WP_Query('s=' . wp_specialchars($_GET['s']) . '&show_posts=-1&posts_per_page=-1');
$count = $tmp_search->post_count;
echo $count . ' results for ' . htmlentities($_GET['s']) . '.';
?>
…and there you have it. A nice functional search results page. For even further refinement, I’m limiting my search to blog posts, and excluding pages by including post_type=post in my query.
RSS feed for comments on this post. TrackBack URL
Jermaine Maree says…
This really came in handy! Was having a similar issue, but it was displaying total posts instead. The posts_per_page=-1 fixed the issue
Thanks!
Reino says…
Great post! Works for me!
Zoinks! Graphics says…
Thanks for sharing. I use it to limit whether or not the navigation links display to save page space. This works great!!
Maria says…
I’m trying to count the number of posts with a particular tag and I’m using the following code:
query(‘tag=TAGNAME’);
echo ‘TAGNAME: ‘ . $my_query->post_count .”;
wp_reset_query(); ?>
I’ve tried adding your code in, in various permutations, but I keep getting out either the total number of posts, or the total posts per page each time when the counts are more than the number of posts allowed per page.
Do you have any suggestions here?
- Maria
Oncle Tom says…
Even simpler:
<?php global $wp_query; echo $wp_query->found_posts ?> results for the search ‘<?php the_search_query() ?>’andy says…
@Oncle Tom — that’s even better, thanks!