Ultimately, this question is off-topic, because the solution has nothing to do with WordPress. Outputting posts in a grid pattern is an HTML/CSS issue, and the best-practice solutions don’t involve putting every three posts inside a separate containing <div>
. Even so, you can do what you want to do, using PHP (which, technically speaking, still makes this question off-topic).
I would start by querying a number of posts divisible by 3, or else setting posts_per_page
to a number divisible by 3. How you do that depends on whether you’re calling a new WP_Query()
for your custom-post type loop, or if you’re filtering pre_get_posts
to modify the default query. Either way, you would use the posts_per_page
query argument.
Then, you can simply define a counter inside the loop, and use it to close/open DIVs as necessary:
<div class="row">
<?php
$counter = 1;
if ( have_posts() ) : while ( have_posts() ) : the_post();
global $wp_query;
the_title();
the_content();
if ( ( 0 == $counter % 3 ) && ( $counter != $wp_query->posts_per_page ) ) {
?>
</div><div class="row">
<?php
}
$counter++;
endwhile; endif;
?>
</div>
The second part of the conditional ensures that you don’t get an empty div after the last row.