Creating PHP counter/rules for WordPress Loop

My Bootstrap grid is 910px spanning 15 columns. Each post in my WordPress loop spans 5 columns.

Here’s the static code:

Read More
<div class="container">     

    <div class="row">

        <div class="span5">
            <p>Post title and image</p>
        </div>

        <div class="span5">
            <p>Post title and image</p>
        </div>

        <div class="span5">
            <p>Post title and image</p>
        </div>

    </div>

</div>

And then here’s roughly how it would look with the loop:

<div class="container">     

    <?php theloop; ?>

</div>

Unless there’s a better way, I think I want to tell WordPress to say:

  • Make a variable $counter
  • For every post, increase the value by one
  • Where the value is one, start the post with div class="row"
  • Where the value is three, start the post with </div> (closing the row)
  • Reset $counter to zero after reaching three and start again

I don’t know how to do this. I’ve asked for help with a similar issue before but I’m totally new to PHP, I’d really appreciate a clear breakdown and explanation.

Thank you!

Related posts

Leave a Reply

1 comment

  1. Try it somehow like this:

     <?php 
     $i=1;
     echo '<div class="row">';
     if (have_posts()) : ?>
               <?php while (have_posts()) :   
               // do stuff ...
               the_post();
               if($i % 3 == 0)
                   echo '</div><div class="row">';
               $i++; endwhile; ?>
     <?php endif; ?>
    

    I didn’t test it, but somehow like this. Use the modulo function.