1

I have a custom post type that I want to use an if/elseif/else statement with. If post count of post type is equal to 1 do X, elseif post count is greater than 1 do Y, else do Z.

This is the code I've come up with so far, but when I add in the count post type the_content and the_title start to pull in normal pages, not custom post types. Also, I'm pretty sure it's not actually counting the posts either. If I remove the if/elseif/else the while loop works perfectly.

PS. I stripped out the code in my while loop to make it more simplified. The normal code is much more complicated for the slider. The slider operates even with one slide so I need the first if statement to omit the slider if only one post.

function getTestimonial() {

    $args = array( 'post_type' => 'testimonial' );
    $loop = new WP_Query( $args );
    $count_posts = wp_count_posts( 'testimonial' );
    if(count($count_posts) == 1) :?>
        <?php the_content(); ?>
        <?php the_title(); ?>
    <?php elseif(count($count_posts) > 1) : ?>
        <?php if ($loop->have_posts()) : while ($loop->have_posts()) : $loop->the_post(); ?>
             <div id="slider">
                <?php the_content(); ?>
                <?php the_title(); ?>
              </div>
        <?php endwhile; endif; ?>
    <?php else: ?>
        <p>No listing found</p>
    <?php endif;
    }

2 Answers 2

3

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
}
1
  • So that worked but silly me forgot to add the while loop to the first if statement. That's why it was pulling in normal posts (facepalm).
    – Heather
    Aug 5, 2016 at 6:30
1

Can you just print_r( $loop ) & print_r( $count_posts ) and see what the output is.

2
  • So I echoed both and got this: pastebin.com/RnVV3EKc
    – Heather
    Aug 5, 2016 at 6:10
  • You can use $loop->post_count to count the number of posts returned.
    – Annapurna
    Aug 5, 2016 at 6:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.