PHP counting loop adding extra row

Viewed 125

I'm trying to wrap every 3 articles in a div so that my HTML would like like this:

<div class="row">
  <article>Article One</article>
  <article>Article Two</article>
  <article>Article Three</article>
</div>
<div class="row">
  <article>Article Four</article>
  <article>Article Five</article>
  <article>Article Six</article>
</div>

Below is my PHP. This is what I currently have, however an extra row is being added at the beginning, which I do not want.

$i = 0;
echo '<div class="row">';
if ($my_query->have_posts()) : 
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<?php if($i % 3 == 0) {echo '</div><div class="row">';}?>

The above prints the following:

<div class="row"></div> //I don't want this to be in the HTML
<div class="row">
  <article>Article One</article>
  <article>Article Two</article>
  <article>Article Three</article>
</div>
<div class="row">
  <article>Article Four</article>
  <article>Article Five</article>
  <article>Article Six</article>
</div>

I tried changing $i = 0 to $i = 1 but this didn't work either. This prints this in the markup:

    <div class="row">
      <article>Article One</article>
      <article>Article Two</article>
    </div>
    <div class="row">
      <article>Article Three</article>
      <article>Article Four</article>
      <article>Article Five</article>
    </div>
    <div class="row">
      <article>Article Six</article>
    </div>

I've tried different number combinations but I couldn't seem to get it simply wrap every 3 articles.

3 Answers
Related