Posts in Columns – A New Twist on an Old Problem

To organize posts into three columns (edit: semantically more correct would be to call it ‘three posts per row’ as this is the way the posts are organized), you first need to generate a column dependant css class for each post; this will be added to the post div within the loop.

The core trick to generate different css classes for posts in the first coliumn, the second column, and the last column:

<?php $column = ($column == '') ? 'first' : (($column == 'first') ? 'middle' : (($column == 'middle') ? 'last' : 'first' )); ?>

This line of code needs to be within the loop, just before the post div.

To achieve more or less the same, you could obviously also use a counter variable and the modulus operator, as i have elaborated on in my earlier article ‘More-Than-Zebra style WordPress loop’. However, the above method is simpler and easier to apply within a single line of code.

The second step is to add this as a css class to the post div:

a – assume a theme without the use of ‘post_class()’; the typical opening div would look like:

<div class="post" id="post-<?php the_ID(); ?>">

This is changed into:

<div class="post <?php echo $column; ?>" id="post-<?php the_ID(); ?>">

b – in a theme using the ‘post_class()’, the new code would look like:

<div <?php post_class($column); ?> id="post-<?php the_ID(); ?>">

Third and last step: to tell the browser what to do with the new css classes, add some styles to style.css of the theme:

/* .first, .middle, .last styling of posts on home page for three column */
.first, .middle, .last { width: 32%; float:left; clear:none!important; }
.first { margin-right: 2%; clear:both!important; }
.middle { margin-right: 2%; }

Final details depend on the existing theme.

edit & ps:
if you just want to mark the first post in each row – for instance to add the ‘clear:both;’ and a different margin there – try to work with:
(example for 5 columns)

<div <?php $column = ($wp_query->current_post%5 == 0) ? 'first' : ''; post_class($column); ?> id="post-<?php the_ID(); ?>">