0

I am trying to create a loop for a custom post type that first calculates how many posts it contains. If it only contains one post, it should simply display the content area of the post. If the post contains more than 1 post it should display the excerpts of all the posts in the loop. Has anyone figured this out?

2 Answers 2

3

https://codex.wordpress.org/Class_Reference/WP_Query#Properties

found_posts is the total number of posts returned by the query.

example code:

<?php
$args = array( 'post_type' => 'your_custom' );
$custom_query = new WP_Query( $args );

if( $custom_query->have_posts() ) {
   $number_of_posts = $custom_query->found_posts; 

   while( $custom_query->have_posts() ) { 
      $custom_query->the_post();

      if( $number_of_posts == 1 ) { 
         the_content(); 
      } else { 
         the_excerpt(); 
      }

   } 

   wp_reset_postdata();

}
?>
1
  • @nick as per your requirements, the answer is correct. Apr 13, 2017 at 6:47
1

Please try this code & let me know the result (I've not tested)

<?php
$post_query = new WP_Query('post_type=post'); // replace the post type with your post type key
$total_posts_found = $post_query->found_posts;

if($total_posts_found < 2 && $total_posts_found > 0){
    if($post_query->have_posts()) : while($post_query->have_posts()) : $post_query->the_post();
        echo '<h1>'get_the_title().'</h1>';
        echo get_the_content();
    endwhile;
    endif;
    wp_reset_postdata();
} else {
    if($post_query->have_posts()) : while($post_query->have_posts()) : $post_query->the_post();
        echo '<h1>'get_the_title().'</h1>';
        echo get_the_excerpt();
    endwhile;
    endif;
    wp_reset_postdata();
}
?>

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.