-4

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();
?>
Francesca
  • 26,842
  • 28
  • 90
  • 153
  • See my anser [here](http://stackoverflow.com/a/31424248/1960712). It's basically same, just `$limit` would be 3 and you have `
    ` instead of ``. Should show you how it's done.
    – Rene Korss Jul 16 '15 at 10:02

1 Answers1

0

Use the modulo operator:

if ($counter % 3 == 0 ){

}

It will be 0 when a multiple of 3

Darren Young
  • 10,972
  • 36
  • 91
  • 150
andrew
  • 9,313
  • 7
  • 30
  • 61