This can be achieved by accessing WP_Query
class properties, available while in the loop, like $current_post
(index of the current post), $post_count
(number of posts displayed), $found_posts
(total number of posts matching query).
By using $current_post
, $post_count
and PHP modulo, like shown below:
<?php if ( $custom_query->have_posts() ) : while ( $custom_query->have_posts() ) : $custom_query->the_post();
$i = $custom_query->current_post;
$c = $custom_query->post_count;
if ( $i % 4 == 0 ) {
// happening for $i being 0, 4, 8 and so on
echo '<div class="row">';
} ?>
// single post markup
<?php if ( $i % 4 == 3 || $i == ( $c - 1 ) ) {
// happening for $i being 3, 7, 11 and so on
// OR condition in case the last one is not a multiple of 4
echo '</div>';
}
endwhile; endif; ?>