Counting posts : $wp_query->found_posts

Sometimes you'll want to display posts in different ways depending on how many results your WordPress query has found. For example, if you're on a category archive page, you might choose to have posts shown in full if there are only one or two results, have titles + excerpts shown if there are fewer than a dozen, and just show clickable titles if there are more than that. Or you might want to run pagination differently depending on how many results your WP query generates - or create a pagenavi-style navigation, where you'll need to know how many results you have in total, not just how many are showing on that page. Even if you're just showing a list of search results, it's nice to be able to say how many results there are.

WordPress has a very easy, but not very well publicised way to do this: $wp_query->found_posts. This returns the number of posts matching the current query parameters. So to show the number of search results found, you'd just need:Search results for <?php echo esc_html($_GET['s']); ?> :
<?php echo $wp_query->found_posts; ?> matching posts found.

Simples.

Share this post:
  • email
  • del.icio.us
  • Facebook
  • FriendFeed
  • LinkedIn
  • StumbleUpon
  • Tumblr
  • Twitter

Posted by Sue on August 2, 2009 in WordPress.

Leave a Reply