• 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.

    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 side 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;
            }
Viewing 2 replies - 1 through 2 (of 2 total)
  • You just need to rearrange things a bit. the_title() and the_content() need to appear after $loop->the_post(); or they won’t work correctly. Do it something like this:

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

    (I also changed wp_count_posts() to $loop->found_posts).

    Thread Starter htausch

    (@htausch)

    Thanks, I figured it out a little later. It was a case of trying to work too late at night.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘How to count custom post types with conditional operators’ is closed to new replies.