How to count custom post types with conditional operators

WP_Query provides some useful properties. There are two of them which you could use:

  • $post_count – The number of posts being displayed (if you not pass posts_per_page argument to WP_Query construct it will return at most 5 posts)
  • $found_posts – The total number of posts found matching the current query parameters (so if you have got 100 posts in database which will fit to the arguments then this property will return 100)

Here is sample of code:

$args = array( 'post_type' => 'testimonial' );
$loop = new WP_Query( $args );
$numposts = $loop->post_count;
if ($numposts == 1) {
    // do X
} else if ($numposts > 1) {
    // do Y
} else {
    // do Z
}