Make loop inside slider divisible

The question:

I’m trying to divide a posts loop in order to show 4 posts per each slide inside a slider.

The code below works good, but since the number of posts in the WordPress panel is dynamic and varies, it breaks and doesn’t close the last item depending on the total number of posts.

Is there a way I can set some sort of counter so it works no matter if there is a total of 8,9, 11, 12… posts?

  <!-- Slider -->
  <div class="slider">

      <?php $argsb = array('post_type'=>'post', 'posts_per_page' => -1, 'post_status' => 'publish');?>
      <?php  $blog = new WP_Query($argsb); if ( $blog->have_posts() ): ?>

      <!-- Slide -->
      <?php  while ( $blog->have_posts() ) : $blog->the_post(); $i++;?>
      <?php if( $blog->current_post % 4 == 0 ) echo "n".'<div class="slide">'."n"; ?>

          <h1><?php echo the_title(); ?></h1>

    <?php if( $blog->current_post % 4 == 3 ) echo '</div>'."n"; ?>
    <!-- end of slide -->

    <?php endwhile; wp_reset_postdata();?>

      <?php endif; ?>

  </div>

Thanks!

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Unfortunatelly, I didn’t understand your question right, but I see only 2 possible problems here. Here you will need to use:

$blog->current_post – current post index
$blog->post_count – total posts

If you need to wrap each 4 posts with a div, and if there are less then 4 posts in the end, wrap them to. To achieve this you need to add another OR condition to the second if statement. Check if the current post is equal to the last post.

//before...
if( $blog->current_post % 4 == 3 )

//after...
if( $blog->current_post % 4 == 3 || $blog->current_post == $blog->post_count - 1)

If you want to wrap each 4 posts in a div and “leave” the remainder, you can add another if statement, which should go first, just after while loop starts.

//your while loop starts 
while ( $blog->have_posts() ) : $blog->the_post();

//break the loop if there are less than 4 posts left
if( $blog->current_post >= $blog->post_count - ($blog->post_count % 4)){
      break;
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment