Josh Kern Josh Kern - 1 month ago 13
PHP Question

Wrap every three WordPress posts in div

I'd like to wrap every three posts in a new row (div) with a total of nine posts on a page. There's an empty row at the end. I thought this (I need to wrap every 4 wordpress posts in a div) would work, but I have more posts on pages 2, 3, 4, etc. Below is a simplified version of my code. $i = 1.

<div class="row">

<?php while ( have_posts() ) : the_post(); ?>

<div class="column">
</div>

<?php if ($i % 3 == 0 ) : ?>

</div> <!-- .row -->
<div class="row">

<?php endif; $i++; ?>

<?php endwhile; ?>

</div> <!-- .row -->

Answer

I used this post (https://www.nosegraze.com/display-wordpress-posts-2-3-columns/) to solve my problem.

$i = 0;

<?php while ( have_posts() ) : the_post(); ?>

    <?php if ( $i == 0 ) : ?>

        <div class="row">

    <?php endif; ?>

    <div class="column">
    </div> <!-- .column -->

    <?php
        $i++;
        if( $i == 3 ) :
        $i = 0; ?>

        </div> <!-- .row -->

    <?php endif; ?>

<?php endwhile; ?>

<?php if ( $i > 0 ) : ?>

    </div> <!-- .row -->

<?php endif; ?>