I have a query which outputs 9 items. I wanted to wrap a div around every 3 items, so I created a simple counter:
if ($counter == 1 || $counter == 4 || $counter == 7){
echo '<div class="client-logo-wrapper">';
}
echo '<img src="'.get_field('client_logo').'" />';
if ($counter == 3 || $counter == 6 || $counter == 9){
echo '</div>';
}
Because the query always outputs 9 items (and there are many items) it works OK. However I have another new query which can output any number of items. It will usually be 3+ but could be 4, 9, 25 etc.
How can I adjust the above loop to attempt to wrap every 3 items in a div, but if it falls short, just wrap in a div anyway?
E.g If there are 8 items, it should wrap them in three divs, one with 3, another with 3, and the final one with only 2.
This is the full code for the wordpress query:
<?php
$counter = 1;
$the_query = new WP_Query(
array(
'post_type' => 'client',
'post_status' => 'publish',
'posts_per_page' => 9
)
);
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
if ($counter == 1 || $counter == 4 || $counter == 7){
echo '<div class="client-logo-wrapper">';
}
echo '<img src="'.get_field('client_logo').'" />';
if ($counter == 3 || $counter == 6 || $counter == 9){
echo '</div>';
}
$counter++;
}
}
wp_reset_postdata();
?>