I am trying to achieve a layout where there are 4 columns in which content is in boxes that are capable of stacking vertically. This means that there are no regular rows (each content box can be different height), only regular columns (content boxes have always the same width).
The problem is – I have no idea how to do it via PHP loops. That’s because I have to put the first post into the first column, the second post into the second column, third one into column nr 3, the fourth one into column nr 4 and then the 5th post goes AGAIN into column 1, etc.
So there are four columns and twenty posts, the newest posts are at the top and the oldest ones are at the bottom.
Here’s a screenshot of what I already have so that you see the irregular rows and regular columns concept:
As requested, my code:
$counter = 0;
for($cols = 0; $cols < 4; $cols++) {
?>
<!-- COLUMN NR <?php echo $cols; ?> -->
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-3 post_box">
<?php
foreach ($post_list as $p) {
$the_post = get_post($p);
$the_title = $the_post->post_title;
$the_content = $the_post->post_content;
if($counter == (0 + $cols) || $counter == (4 + $cols) || $counter == (8 + $cols) || $counter == (12 + $cols) || $counter == (16 + $cols) ) {
?>
<!-- POST NR <?php echo $counter; ?> WITH ID <?php echo $p; ?> -->
<div class="post_container">
<a href="<?php echo get_permalink($the_post->ID); ?>">
<div class="row postbox_title">
<div class="col-xs-12 title_col">
<h2><?php echo $the_title; ?></h2>
</div>
</div>
<div class="row postbox_content">
<div class="col-xs-12 content_col">
<div class="post_content">
<?php echo '<p>'.$the_content.'</p>'; ?>
</div>
</div>
</div>
</a>
</div>
<?php
}
$counter++;
}
?>
</div>
<?php
}
Here’s a screenshot of my code to make it more readable:
http://scr.hu/5z5a/icinl
3
Answers
Okay, thanks to @Chorna I managed to fork his answer and fix my problem! Thank you for that :).
I loaded the posts into an array this way:
Then I displayed them like this:
Thank you all for your help!
It’s Masonry css you are looking for, you can do it with only html and css.
You can divide the posts into 4 arrays, and then use a foreach to create the cols. Something like (pseudocode):
You can see the code output here.