Wrap every 3 posts in a div (without empty div)

The following code inserts a div every 3 posts. But if there are 3 posts, an empty div is added. How do I prevent the empty div?

Thanks

 <div class="row thirds">
 <?php
 // Find connected pages
 $connected = new WP_Query( array(
 'connected_type' => '2-col-module_to_pages',
 'connected_items' => get_queried_object(),
 'nopaging' => true,
  ) );

  if ($connected->have_posts() ) : while ($connected->have_posts()) : $connected->the_post(); ?>

   <h2><?php the_title();?></h2>

  <?php $counter++;
  // add row div every 3 posts
  if ($counter % 3 == 0) {
     echo '</div><div class="row thirds">';
     }
    endwhile;  wp_reset_postdata(); endif; ?>
  </div>

Related posts

Leave a Reply

1 comment

  1. You can check the total amount of posts that the query returned by using `$connected->$found_posts. So you could use the following code to prevent the div from being inserted at the end:

    if ($counter % 3 == 0 && $counter != $connected->$found_posts) {
         echo '</div><div class="row thirds">';
    }