1

Is it possible to require a minimum number of results in a wordpress loop? And if the loop doesn't return enough posts, then you show a placeholder?

Basically, I need to show 8 posts in a grid. If there aren't enough posts to fill all 8 spaces, then I want to show a gray box where a post should be. So if there are only 6 posts, there will be 6 post boxes and 2 gray empty boxes. It seems like I need to:

  1. Count how many posts were returned in the loop
  2. If there are less than 8 posts, then subtract that count from 8
  3. Add X number of placeholders at the end of the loop

I'm just not sure how/where to add the correct number of placeholders. Here's what I've got:

      <?php $args= array(
        'post_type' => 'beer',
        'posts_per_page' => -1
        );

        $beer2_query = new WP_Query( $args ); if ( $beer2_query->have_posts() ) : 

            $count = $beer2_query->post_count; 
            $i = 1; ?>

            <div class="row"

              <?php while ( $beer2_query->have_posts() ) : $beer2_query->the_post(); ?>

                <div class="col-sm-3">
                    <div class="card">
                        <h3><?php the_title(); ?></h3>
                    </div>
                </div>

             <?php $i++; endwhile; wp_reset_postdata(); ?>

             <?php if ($count < 8) { 
             $placeholder_count = (8 - $count);

// how do I echo out placeholder boxes that equals the placeholder_count total?

             } ?>
          </div>

          <?php endif; ?>  

Thank you!

LBF
  • 1,133
  • 2
  • 14
  • 39

2 Answers2

0

Instead of <?php if ($count < 8) { // add placeholders! } ?>

Try <?php while($i >= 8) {// add placeholders!; $i++; }}

That way you are using the counted number of posts, and adding placeholders until it equals 8.

  • Thank you! I wasn't sure where to put this. I tried replacing the line you mentioned, and also moving it into the loop and out of it, but no luck. – LBF Jun 28 '17 at 21:43
0

Instead of using the if statement after the while loop, you can replace it with this. The loop will only run if the post count is less than 8 and will run however many times the difference between 8 and the post count is. You can also remove the $i counter because it won't serve a purpose.

for ($x=0; $x < 8 - $count; $x++) { 
    // Insert placeholder
}
dukedevil294
  • 1,285
  • 17
  • 31
  • Thank you! That worked perfectly for me. I replaced all my code at the end and just put your code after the closing `endwhile`. – LBF Jun 28 '17 at 21:38