Horizontally Sequenced Display Order for WordPress Posts in Two Columns
Posted on August 4, 2008 in WordPress by Jeff Starr
Most WordPress-powered blogs display posts in sequential order within a single column. Like this, for example:
![[ Diagram: Default WordPress Post Display Order ]](http://perishablepress.com/press/wp-content/images/2008/horiz-order/horizontal-order_default.gif)
But what if you wanted to display your posts in two columns, sequentially ordered from left to right? For example:
![[ Diagram: Horizontally Sequenced WordPress Post Display Order ]](http://perishablepress.com/press/wp-content/images/2008/horiz-order/horizontal-order_php.gif)
This is easily accomplished using two default loops and the rewind_posts() function. The first loop will display the posts in the first column, while the second loop will display the posts in the second column. To do this, we use PHP’s modulus operator to filter out every other post from the first loop, which will display posts as follows:
- the first most recent post
- the third most recent post
- the fifth most recent post
..and so on. Meanwhile, the second loop will feature all of the posts that were filtered out of the first loop:
- the second most recent post
- the fourth most recent post
- the sixth most recent post
and so on, depending on the specified number of displayed posts. As you can see, this configuration divides the posts into “odd” and “even” groups. Note that there is nothing inherently “odd” or “even” about the posts in either group; we are arbitrarily assigning “oddness” and “evenness” based on location of each post within the default sequence. Thus, posts with odd-numbered IDs may appear in the “even” loop and vice versa. having said that, let’s examine the code that will make this happen:
<?php if (have_posts()) : while(have_posts()) : $i++; if(($i % 2) == 0) : $wp_query->next_post(); else : the_post(); ?>
<div id="left-column">
<h1><?php the_permalink(); ?></h1>
<?php the_content(); ?>
</div>
<?php endif; endwhile; else: ?>
<div>Alternate content</div>
<?php endif; ?>
<?php $i = 0; rewind_posts(); ?>
<?php if (have_posts()) : while(have_posts()) : $i++; if(($i % 2) !== 0) : $wp_query->next_post(); else : the_post(); ?>
<div id="right-column">
<h1><?php the_permalink(); ?></h1>
<?php the_content(); ?>
</div>
<?php endif; endwhile; else: ?>
<div>Alternate content</div>
<?php endif; ?>
With that code in place, oddly numbered posts will appear within a division identified with an attribute of id="left-column". Likewise, even-numbered posts will appear within a division identified with an attribute of id="right-column". Thus, we may apply the following CSS to position the divisions as two adjacent columns:
div#left-column {
width: 333px;
float: left;
clear: none;
}
div#right-column {
width: 333px;
float: right;
clear: none;
}
Of course, when it comes to configuring the WordPress loop and styling your page with CSS, anything is possible. Feel free to experiment and adapt this technique to suit your own diabolical purposes ;) For now, let’s continue with an explanation of the functionality behind this dual-loop technique.
Technical Breakdown
Perhaps the most straightforward way to explain the dual-loop code is to break it down line-by-line via comments placed within the code itself:
// initiate the default wordpress loop as usual
<?php if (have_posts()) : while(have_posts()) :
// set a count variable to increase with each loop
$i++;
// test the variable modulus against a zero value
// odd values return true, even values return false
// see proceding discussion for more information
if(($i % 2) == 0) :
// skip to next post if variable is an even number
$wp_query->next_post();
// display the post if variable is an odd number
else : the_post(); ?>
// open a division for the left column
<div id="left-column">
// display the title of the post
<h1><?php the_permalink(); ?></h1>
// display the post content
<?php the_content(); ?>
// close the division
</div>
// close the first if statement
<?php endif;
// close the loop
endwhile;
// if there are no posts that meet the criteria
else: ?>
// display some alternate content
<div>Alternate content</div>
// close the second if statement
<?php endif; ?>
// reset the count variable to zero
<?php $i = 0;
// reset the loop
rewind_posts(); ?>
// the second loop is essentially the same as the first
// the only difference is that we are testing the count variable against a non-zero value to display only even numbers
<?php if (have_posts()) : while(have_posts()) : $i++; if(($i % 2) !== 0) : $wp_query->next_post(); else : the_post(); ?>
// and of course a unique div id for the right column
<div id="right-column">
<h1><?php the_permalink(); ?></h1>
<?php the_content(); ?>
</div>
<?php endif; endwhile; else: ?>
<div>Alternate content</div>
<?php endif; ?>
As for the crazy PHP modulus operator ( % ), suffice it to say that its purpose is to test the oddness or evenness of the $i variable. The modulus operator returns the numerical remainder resulting from the division of the $i variable by the specified number (“2” in this case). In the first loop, because all even post numbers are evenly divisible by two, the modulus is equal to zero and thus the evenly numbered posts are skipped until the next loop. In the second loop, the odd post numbers are not evenly divisible by two, resulting in a non-zero numerical remainder. Thus, in the second loop, we test that the modulus is not equal to zero, thereby skipping the oddly numbered posts. Perhaps this numerical pattern will help clarify the concept:
- Post #1: $i = 1 [remainder of 1/2 = 1]
- Post #2: $i = 2 [remainder of 2/2 = 0]
- Post #3: $i = 3 [remainder of 3/2 = 1]
- Post #4: $i = 4 [remainder of 4/2 = 0]
- Post #5: $i = 5 [remainder of 5/2 = 1]
- Post #6: $i = 6 [remainder of 6/2 = 0]
- Post #7: $i = 7 [remainder of 7/2 = 1]
- Post #8: $i = 8 [remainder of 8/2 = 0]
From this we can see how testing the modulus against zero (or non-zero) results in two groups of (odd and even) numbers. For more mental torture, here is more information on the PHP modulus operator. But enough of this boring math stuff — let’s move on, shall we?
Pure CSS Method
As the astute reader may have observed, displaying two columns of horizontally sequenced posts is also possible using a single, default WordPress loop and a little bit of CSS. Consider the following code:
<div id="container_division">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="post-block">
<h1><?php the_permalink(); ?></h1>
<?php the_content(); ?>
</div>
<?php endwhile; else: ?>
<?php endif; ?>
</div>
With each post enclosed within a “post-block” division (i.e., <div class="post-block">), we can achieve a two-column post-display similar to that generated via the dual-loop method by declaring a width for each of the post blocks and then placing them within a fixed-width container division. Or, to express this idea visually:
![[ Diagram: Two Columns of Horizontally Sequenced Divs ]](http://perishablepress.com/press/wp-content/images/2008/horiz-order/horizontal-order_css.gif)
With all of the post-block divisions floated to the left, they will automatically “stack” according to the diagram. Here’s an example of CSS that would make this work:
div.post-block {
width: 333px;
float: left;
clear: none;
}
div#container_division {
width: 700px;
}
As useful as this “pure-CSS” technique happens to be, it is not as flexible as the dual-loop version. Independently functioning loops provide greater control over layout and thus greater design flexibility. For example, using two individual loops, the post columns need not appear side-by-side, but may be placed anywhere on the page.
Peace Out
That’s it for this Perishable Press tutorial. If you have any questions, concerns, or criticisms, please share them in the comments section for this article. As always, thanks for reading! :)
Related articles
- Fruit Loop: Separate any Number of Odd and Even Posts from any Category in WordPress
- Super Loop: Exclude Specific Categories and Display any Number of Posts
- Display Random Posts from Specific Tags or Categories
- Multiple Loops and Multiple Columns with WordPress, (X)HTML and CSS
- Display the Total Number of WordPress Posts, Comments, and Categories
- How to Display Your Twitter Posts on Your WordPress Blog
- 6 Ways to Customize WordPress Post Order
Oh you are turning to ASCII art I see :p
More seriously, I would have done the second method (Pure CSS) spontaneously. I mean, isn’t the first one too much complicated for achieving such a simple result ? :o
Now, while it won’t do exactly the same result, I would like to underlign that Safari & Firefox already support the CSS3 multi-column specification. Yummy.
Note: the
preformatting is perfect in my NetNewsWire.And now, what about some quick sketches instead of ascii art ? :)
There is nothing wrong a little ascii art! ;)
@Louis: Ah, but that’s the whole point — the result need be simple only if you are using the CSS-only method. As mentioned in the article, splitting the posts up via the dual-loop technique provides much more control over layout and additional functionality: category exclusion from one or both loops, limiting post count in either loop, and non-adjacent column positioning, for example, are all best handled at the PHP level. Don’t get me wrong, CSS is a great alternative if you merely need two columns of horizontally displayed posts. And, yes, that fruity new CSS3 multi-column business is looking extra-extra tasty (I can’t wait)!
Oh! I LOVE it! I needed to see this. WP is virtually forcing me to delve deeper into PHP because I can’t code my way out of everything (ie your CSS technique vs your php technique) so these little tutorials are the best. Thanks a ton. :)
Hi, thanks for the code. I got an error message after replacing the loop with your double code though (the first one):
Parse error: syntax error, unexpected T_ENDWHILE in /html/wp-content/themes/classic2/index.php on line 53
Hi nomad1, I just double-checked the code on one of my sites and it works fine. One thing you need to watch for when replacing an existing loop is that you remember to delete all traces of it. This includes any closing
endwhileandendifstatements. If not removed when you add the new code, there will be redundant closing statements and you will get errors similar to the one in your comment.@Erika: Always a pleasure! :)
Thanks a lot Jeff, that was the reason. I have overlooked the last part of the loop!
What if, instead of having the columns read from left to right, you wanted them to read from top to bottom then move over a column and proceed top to bottom, so:
--post 1-- --post 3----post 2-- --post 4--Maybe I’m over thinking this but would you do something like:
count = 1BEGIN LOOP
if count = 3 thenend ifCOUNT++or is there a simpler way to do this with the rewind loop function and the query posts?
@nomad1: my pleasure — glad to hear you got it working :)
@Michael: I would handle something like that with either CSS or via two loops for greater flexibility. I guess it all depends on page design. To use the dual-loop method above, you would simply omit the crazy modulus functionality and position the
divs adjacently. There are other ways of doing this, of course — it all depends on your needs.I think a dual-loop method would be great, I’m just not sure how to start the second loop at the 3rd posts.
By the way, I just discovered your web site today, and I’m really enjoying the articles, thanks.
Michael
Drop me an email (using one of the methods below) describing your desired loop structure and I will see if I can come up with something for you.
Regards,
Jeff
I’ve been at the crossroads PHP vs CSS solution. I went the PHP way and the steps are pretty much the same as your tutorial. The only difference is instead of dual-looping posts, I used it on displaying two-columned Categories.
Check it out: http://www.hotelsandtravel.org
I am building a WP theme. Your tutorial has quite solved my troubles :) but I am still missing something.
This image should clarify what I’m trying to do: http://img352.imageshack.us/img352/5196/examplewr6.jpg
Basically Post1 is my latest post in the blog. It’s shown big while posts from 2 onwards use a different style and are listed in two columns. Posts 2 and 3 get to show title and excerpt with their own style. Posts from 4 to 11 show only the title (with a third different style).
In your tutorial you have created two loops in order to list the posts in two columns..do I need 5 loops to achieve my goal?
Hey Stefano,
I think 5 loops would be the way to go, and it should keep things simple.
Hi Michael,
the idea of the 5 loops seems great but I keep on getting errors while tweaking my loops.
What i’m doing is:
1. tell the first loop to show the first post only(which will be my ‘featured’ post).
2. tell loop 2 to show post 2 and loop 3 to show post 3. The two articles are displayed side by side.
3. tell loop 4 to show even posts starting from post 4.
4. tell loop 5 to show odd posts starting from post 5.
(A visual scheme linked in my previous message).
I thought I could achieve this result by using the loop structure shown above adding strings such as numberposts= and offset= but apparently I know too little of php to figure out how to use those..could anyone please help out to put these guys in place?
tnx
I mean…I am pretty sure I could use this code for the first 3 loops:
MYCONTENT
But cannot use this to loops 4 and 5 as they should load the residual posts in horizontal sequence (Even and Odd)…and have offsets.
@Stefano: I think three loops (at most) should be all that you need to accomplish this layout. If you are still needing help with this, send an email and I will do my best to help you out. :)
Cheers,
Jeff
Would it be possible to have 3 columns?
Like this?
–post 1– –post 2– –post 3–
–post 4– –post 5– –post 6–
Why the need for all this counting and columns.
I imagined there would be away to achieve this result by telling the loop to display:inline.
Anyone found a way to do this?
@Martin: In the article, I discuss a way to display horizontal posts using CSS only. Basically, rather than using
display:inline;or some fancy loop configuration, you simply float each post block in the same direction and setcleartonone. There is a bit more to it than that, so you might want to read the article for a better explanation.oops! sorry for my lack of tenacity in not even reaching the end of your article! Thanks for your speedy reply.
Any ideas about the 3 column thing?
@Martin: no problem, my articles tend to be rather long!
@Matt: I think the easiest way to accomplish a three-column horizontal layout would be to use the CSS method described in the second half of the post. Let me know if you need any help with this.
Hi i want to use this code on my blog. but not for all post.
I want 3 or 4 full posts and then post in double column
How?
Hi Jeff,
first of all very nice site! I’ve read a couple of articles before coming to this page. So I subscribed to your RSS feed.
Now for the purpose of this comment: I noticed nobody asked where you have to paste this code, so my question will seem stupid… Where do I paste this code? In a theme file or Wordpress core files? Or is this tutorial for people building their own themes from scratch?
I read the article 3 times and I couldn’t find the answer to my question. Everything else is very easy to understand, in my defense. :D And you explained it well, in my offense. LOL
Thanks in advance,
Tony. (I hope you don’t mind the keyword phrase in the name field)
Hi Tony, thanks for the kind words, but to be honest, the keyword commentator link is a bit much.. I tend to delete comments like this, but since you seem genuine, I will let it slide. [Update: at Tony’s request, I have replaced the keywords with his name]
As for the location in which this code must be placed, that would depend on your setup. Typically, you put the PHP/XHTML in one or more of your theme files, and then place the CSS in the theme’s CSS file.
You do raise a good point with this comment; I tend to assume a certain level of familiarity with web design for my readers, but perhaps I should take the time to reach down a little further.. (no offense intended!;)
Thanks for the explanation Jeff. I will try it on my local test site when/if I feel that I’m up to the task. And no offense taken, we all start somewhere, and there’s always someone more knowledgeable than us, no matter how smart we think we are. hehe
Sorry about the name thing. I don’t want to look like a spammer. I’m just new (read stupid). Thanks for being honest about it.
Any time, Tony — you are always more than welcome here! Thanks for the follow-up comment! :)
I seriously don’t understand the logic behind the “I use dirty keywords linking in my comment — suggesting that the purpose of my whole comment is to abuse PP’s ranking — but I apologize for being a jerk at the end.
You wouldn’t drive into someone’s house on your motorcycle, have a nice conversation with the house owner, and then leave a complete mess behind you and just say “oh I hope you don’t mind “.
That’s unpolite as hell, and worst, that’s illogical to me!
@Louis: I agree with you, but Tony has taken the time to email me about this with a request to replace the keywords with his name. From his email, I think he is sincere and that the mistake was genuine. Thanks for keeping ‘em honest, though! ;)
Thanks Jeff!
Hi, I just found your blog tonight and it’s certainly bookmark worthy, so thanks!
Compliments aside, I’m having problems with this tut. The container div is conflicting with the content div of the theme I’m using. Surely I’m not doing this correctly, so if anyone can help me with this it would be greatly appreciated!
I want to use the 2nd method in this tut because I want to simply stack 4 columns instead of the two given in the first method. Perhaps this just doesn’t work anymore with the latest version of WP? Either way, if you can push me in the right direction - thanks in advance :]
Chris
Chris> Sounds like you already know that you’ll have to fix the container div conflict you’ve got. Can’t have 2 divs with the same ID and expect them to behave differently, so you’ll have to rename one of them and update the CSS to reflect the name change accordingly.
I used the Pure CSS method above (if that’s what you meant by 2nd method). It’s just maths really - take your container width and divide it up into as many columns as you need. Don’t forget to include any padding/margins in your calculations!
Hope this helps.
Martin: Both of the divs have different IDs, but the problem seems to be with how the ‘content’ div handles what the new div ‘container_division’ lists. It causes the content div to act like it has no actual content in it and just shows the header with the footer directly underneath. Perhaps this will be solved by setting a height to the content div, but i haven’t tried anything yet in hope someone can provide me with a legitimate fix. Hopefully you understand my problem somewhat more and can give me some more advice. Thanks so far :]
Chris: Not sure exactly what the issue is (perhaps someone else can be more specific in their assistance) but the following article was very helpful whilst working with this tutorial. Check out the overflow properties of your divs.
http://warpspire.com/tipsresources/web-production/css-column-tricks/
@Chris: There are so many different things involved with any given layout that it is difficult to troubleshoot and solve problems without a working example to look at. I am sure that someone here would be able to help you if you provided a link to a test case demonstrating the issue.
Hey guys, thanks for getting back to me. I just tried it out using a new theme and it seems to be working fine so far! If I run into bother and require your assistance once more, I’ll be sure to check back in, but for now, that is all. :] Keep up the great work, it’s much appreciated!
I want to have 3 columns going horizontally, so, post 1, post 2 and post 3 all on the same line. I just wanted to use CSS and use the float method but it all just stacks vertically no matter what I do. It’s not width or padding causing it, do you have any suggestions? It’s really driving me quite bonkers :)
@Chris: Great to hear that you got it working! Thanks for the follow-up! :)
@Frances: See comment #38; the idea expressed there would apply to your question as well..
Thanks a lot for this tutorial, I had been looking for it for a long time;
but I’m not able to make it work out properly… http://www.boqueria.eu/wordpress/ if you have any idea of what’s my problem I would realy apreciate (why the second row is not in its place?)
@FloiT: your site is looking great! It looks like you have resolved the second-row layout issue, yes?
thanks a lot for you comment, mr. Starr (the site is under constructionand it will be, I think, for at least one month).
Yes, I could solve the problem after three days trying it ! ;) I think this is the best way to learn things (With the help of priceless sites like yours, of course!)
Hi mate, these stuff is amazing! I really appreciate what you wrote here :-)
I was wondering if you could help me please with a little issue I’m having on this blog: http://www.travelgeneration.com (actually I’m testing it on: http://www.travelgeneration.com/blog/new-blog), here’s the deal:
I’ve got a last post which I want to show it with a different style (”latestPost” class), then I pause the loop, div’s in between I continue the loop and show 6 more posts -class =”recentPosts”- (without telling the loop to show 6 more, only by stablishing it on the reading settings: post = 7) stating not to duplicate the first post.
When I click on “next page” it shows the same structure on the following 7 post; but I want to display 6 more instead with the class “recentPosts”.. so what I’ve done is to determine that the first div .latestPost is only displayed if its home page. Now the challenge is to display 6 posts rather than 7 (as it was set on the reading settings). Do I explain myself?
Hope you can help me mate,
Thanks again!
Joaquín.-
hello.
I am trying to do the 3-column thing… what do you mean by “use the CSS method described in the second half of the post”.
thank you!!
@will: In the article, the second half of the post covers a “Pure CSS Method” for producing the 2-column layout. By extrapolating this technique, it is possible to create any number of columns featuring horizontally sequenced post order. Simply adjust the block widths so that three will fit inside of your fixed-width parent container and you are good to go.
@Ozh: Post now updated with actual image graphics instead of that atrocious ascii art! ;)
Just want to thank you. This was the most useful post about this subject. So it helped me a lot to create our webpage http://www.solooyun.com. I’ll will also subscribe to your RSS. Thanks again…
@tolga: It is my pleasure — I am glad the article was able to help you. I see what you have done with the technique on your site and I think it looks great. Well done, and thanks for subscribing! Cheers! :)
Hi Jeff, first thanks for your tutorials , those and the entire blog are very usable, congratulations for this great proyect you have, so, im displaying 10 post per page and im using the second metod (two columns) and it works fine exept for one thing, one of the posts breack on the page, ok explained = in the first page the first 2 posts are in the same row so the follow 3 and 4 in the second row but the post number 5 is in one row and the 6 and 7 in the follow row , 8 and 9 in the follow and then the post number 10 in the last row.
Is there something i can do to avoid this and to get the posts ordered correctly in both columns, 2 in each row.
This is my code :
<a href="" title=""><img src="ID, "Thumbnail", true);?>" width="50" height="50" border="0" align="left" hspace="4" /></b></a>this is the page , you can see the example there and in the pages
http://muyatractivo.com/magazine/
Thanks a lot
Greetings from Mexico
I suspect that on non-CSS, text based browsers, you have sacrificed the order. I bet they will appear 1 3 2 4 or something. You should add a statement about that, or ensure a browser independent solution, that while not delivering two columns (thank God,) will preserve the intended order.
@jidanni: Only the first, PHP method will produce non-sequential post order on non-CSS browsers. The second, CSS-only method does not alter the underlying post order and will thus display the posts correctly when CSS is not available. Good point!
Ok.. I’m not entirely sure that I can explain this so it makes sense, but I’m going to try.
In my sidebar I have a separate category of posts pulled out from the main posts, and want to use this loop method to display them instead of having them in a single line, but for some reason it’s not working. I’m sure it’s something entirely stupid I’ve messed up, but I can’t figure it out and I am desperate to get this thing finished. Help?
Hi Jeff,
Thanks! This is exactly what I needed. I was unsure if I would have trouble using a query before the loop to only pull posts from one category but it’s working great! I do have a question and I’m not sure if it’s related to my code or yours.
I can use the_content or the_excerpt but I can’t get the_content(’Read More…’) to work. And I did double-check to make sure the more tag was actually in the posts. Any ideas?
Thanks again!
Kim
Hi Kim,
Not sure, but I do know that I have encountered this issue as well. One easy workaround is to simply create your own “more” links. Something like:
<a href="<?php the_permalink(); ?>" title="Continue reading this article">Read more</a>Does the same thing, and you could even target the more tag directly by appending a “pound-more-dash-ID” to the permalink:
<a href="<?php the_permalink(); ?>#more-<?php the_ID(); ?>" title="Continue reading this article">Read more</a>Regards,
Jeff
Hi Jeff - Thanks! That’s what I ended up doing. :-) I am also using the Advanced Excerpts plugin with this so there is more control over the excerpts.
Thanks again for a great tutorial.
Anytime, Kim — it is my pleasure to help! :)