Reputation: 73
I want to create a loop for my posts which wraps a and class to every three posts group. The tricky part is that there are 3 different classes which need to keep looping.
So, basically it should create a div with a class of "right" wrapping around the first 3 posts and then a second div with a class of "left" wrapping around the next 3 and a third div wrapping around the next 3 ones after that.
This pattern needs to repeat as the posts go on.
It will look something like this:
<div class="right">
<div>Post 1</div>
<div>Post 2</div>
<div>Post 3</div>
</div>
<div class="left">
<div>Post 4</div>
<div>Post 5</div>
<div>Post 6</div>
<div class="inner-div"></div>
</div>
<div class="middle">
<div>Post 7</div>
<div>Post 8</div>
<div>Post 9</div>
<div class="inner-div"></div>
</div>
And repeat
Ive tried this: PHP loop: Add a div around every three items syntax But its only adding the first class and then repeating the second class.
Upvotes: 0
Views: 1345
Reputation: 4356
I have modified the reference answer you linked to fit according to your requirement.
Original answer: PHP loop: Add a div around every three items syntax
<?php
$i = 1;
$j = 0;
$target_class = array( 'right', 'left', 'middle' );
//added before to ensure it gets opened
echo '<div class="'.$target_class[$j].'">';
if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post();
// Do whatever you want here.
// if multiple of 3 close div and open a new div
if($i % 3 == 0) {
// echo inner div if target class is not right
echo ( $j != 0 ? '<div class="inner-div"></div>' : '' );
// send back to first position if it goes above the third position
$k = ( ++$j == 3 ? 0 : $j );
echo '</div><div class="'.$target_class[$k].'">';}
$i++; endwhile; endif;
//make sure open div is closed
echo '</div>';
?>
This should work. Did not test it though.
Edit: Tested and fixed. Code is working
Edit: 2 Update code to entertain request from comment.
Edit: 3 Update code to entertain request from comment.
Upvotes: 1