I am wrapping every 3 elements in my loop in a wrapper div like this:
$query = array(
'post_type' => 'post',
);
$i = 1;
$posts = new WP_Query( $query );
$out = '<div class="wrapper">';
if ($posts->have_posts()){
while ($posts->have_posts()){
$posts->the_post();
$out.= '<div class="content">
//content here
</div>';
if($i % 3 == 0) {
$out .= '</div><div class="wrapper">';
}
$i++;
}
}
$out .= '</div>';
wp_reset_postdata();
return '<section>'.$out.'</section>';
Which creates a good wrapping html minus one little thing that's bothering me:
<section>
<div class="wrapper">
<div class="content"></div>
</div>
<div class="wrapper">
<div class="content"></div>
</div>
<div class="wrapper"></div>
</section>
If I have exactly 6 posts (or any multiple of 3, and modulo is doing this like it should) I'll get an extra empty wrapper. Which is really not needed.
So what conditional should I include in my query to ensure that I don't get empty wrappers?
Add the wrapper inside: