Wrap every 3 posts in a div (no empty div)
The following code inserts a div every 3 posts. But if there are 3 posts an empty div is added. How to prevent empty div?
thank
<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>
+3
source to share
1 answer
You can check the total number of posts returned by a request using `$ connected → $ found_posts. Thus, you can use the following code to prevent the div from being added at the end:
if ($counter % 3 == 0 && $counter != $connected->$found_posts) {
echo '</div><div class="row thirds">';
}
0
source to share