I am struggling to get the following function work properly. I am trying to configure a loop inside WordPress with wrapping every first 3 items in a div. After that it should wrap the next 2 items in a div. and so on.
What i want to achieve:
<div class="row">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
<div class="row">
<div class="item"></div>
<div class="item"></div>
</div>
<div class="row">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
<div class="row">
<div class="item"></div>
<div class="item"></div>
</div>
What i tried with php
<div class="row">
<?php
$i = 0;
while ( have_posts() ) : the_post(); $i++; ?>
<div class="item"></div>
<?php if( $i % 3 == 0 ): ?>
</div><!-- .row -->
<div class="row">
<?php endif; ?>
<?php endwhile; ?>
</div>
Finally this wraps up every third element into a new row. Hopefully somebody can give me the hint to help me with this to get the second repeater (2 items in a row) working.
2
Answers
You don’t want to use modulus for this, since the row count is different for each group. Instead, reset your counter, and set a variable for the number of rows that will change every time you change groups:
I endorsed restarting the counter variable every time an new row is created and setting the new row limit to 5 minus the current row limit. This will alternate between 2 and 3 mathematically.
To avoid writing div tags when there are no posts to print, only start printing row tags inside the loop and only print a condition row ending tag if the loop has done at least one iteration.
Code: Demo
Output: