Multiple Loops and Multiple Columns with WordPress, (X)HTML and CSS

Published Monday, September 1, 2008 @ 7:49 am • 26 Responses

Recently, I have been getting a lot of requests for multiple-loop configurations in WordPress. It seems that multiple-column, multiple-loop configurations are in high demand these days, especially ones that display posts like this:

  • First column, first loop: display posts #1-5
  • Second column, second loop: display posts #6-10
  • Third column, third loop: display posts #11-15

Using WordPress and a little CSS, this configuration is relatively easy to accomplish. Let’s cut right to the chase..

Step 1: Multiple-Loop, Multiple Column PHP Configuration

The first thing we want to do is replace the standard WordPress loop with the following code:

// FIRST LOOP: display posts 1 thru 5
<?php query_posts('showposts=5'); ?>
<?php $posts = get_posts('numberposts=5&offset=0'); foreach ($posts as $post) : start_wp(); ?>
<?php static $count1 = 0; if ($count1 == "5") { break; } else { ?>

<?php the_title(); ?>
<?php the_content(); ?>

<?php $count1++; } ?>
<?php endforeach; ?>


// SECOND LOOP: display posts 6 thru 10
<?php query_posts('showposts=5'); ?>
<?php $posts = get_posts('numberposts=5&offset=5'); foreach ($posts as $post) : start_wp(); ?>
<?php static $count2 = 0; if ($count2 == "5") { break; } else { ?>

<?php the_title(); ?>
<?php the_content(); ?>

<?php $count2++; } ?>
<?php endforeach; ?>


// THIRD LOOP: display posts 11 thru 15
<?php query_posts('showposts=5'); ?>
<?php $posts = get_posts('numberposts=5&offset=10'); foreach ($posts as $post) : start_wp(); ?>
<?php static $count3 = 0; if ($count3 == "5") { break; } else { ?>

<?php the_title(); ?>
<?php the_content(); ?>

<?php $count3++; } ?>
<?php endforeach; ?>

That’s the juice right there. We have three loops, each displaying five posts. The first loop displays the first five posts, the second loop displays the next five posts, and the third loop displays the next five posts. Thus, this multiple-loop configuration displays the most recent 15 posts, each of which being unique.

To change the number of posts displayed for any given loop, you will need to edit three different arguments:

  • showposts=5
  • numberposts=5&offset=0
  • $count1 == "5"

Notice the pattern here: for the first loop, we are showing the first five posts. The number of posts is set by the showposts=5, numberposts=5, and $count1 == "5". The first two arguments are self-explanatory, and the third simply stops the loop when the indicated number of posts has been processed.

Thus, to change the number of posts displayed in the first loop, change the number “5” to the desired number of displayed posts. After that, you need only specify the loop offset parameter, which lets WordPress know how many posts to skip before displaying the specified number of posts. For example, an offset value of “0” is used in the first loop so that no posts are skipped and the first five posts are displayed. Then, because the first loop displays the first five loops, we use an offset value of “5” in the second loop so that the loop skips over the first five posts and displays the next five posts in the sequence. Likewise, an offset value of “10” in the third loop ensures that the first 10 posts displayed in the first two loops are not repeated. Thus, if you wanted to display 10 posts in the first loop, the offset value in the second loop would be “10”.

Step 2: Multiple-Loop, Multiple Column (X)HTML Configuration

Now that we have the PHP in place, we are ready to add the (X)HTML markup required for the final three-column configuration. There are many ways to accomplish this, this is merely one of them:

<div id="column_01">

	<!-- FIRST LOOP -->

</div>

<div id="column_wrap">

	<div id="column_02">

		<!-- SECOND LOOP -->

	</div>
	<div id="column_03">

		<!-- THIRD LOOP -->
	
	</div>

</div>

Here, each of the three loops will be placed into its own div, which then will be styled with a little CSS to transform it into one of the three columns. Note that you may want to change the id names of the divisions to better represent the particular semantics of your document. Now let’s move on to the CSS..

Step 3: Multiple-Loop, Multiple Column CSS Configuration

The final step in the tutorial is to style the markup with CSS. Nothing too fancy, really. Creating the columns is merely a matter of floating the individual divs and applying a width to each of them:

/* three column layout */
div#column_01 {
	float: left;
	clear: none;
	width: 30%;
	}
div#column_wrap {
	float: right;
	clear: none;
	width: 60%;
	}
	div#column_02 {
		float: left;
		clear: none;
		width: 45%;
		}
	div#column_03 {
		float: right;
		clear: none;
		width: 45%;
		}

The trick here is to use width values that will create the correct column widths. The values used in the example produce three columns of approximately equal width. A great way to check how your width values are actually affecting layout is to add the following line of code to each selector:

border: thin solid red;

Adding that declaration to each of the four code blocks will create an outline around each of your divisions, enabling you to see easily the amount of space between each column. I use this trick all the time — it’s a real time-saver. Beyond that, you may specify the width in any units that you wish (e.g., em, px); no need to stick with percentages!

Warp Speed..

There is SO much you can do with WordPress, PHP, (X)HTML, and CSS. The possibilities are virtually endless. The multiple-column configuration presented in this article is a great starting point for creating more elaborate and sophisticated page layouts. Experiment and have fun!!


Dialogue

26 Responses Jump to comment form

1Erika

September 3, 2008 at 11:58 am

Check your second set of code tags… it says “First Loop… Second Loop.. Second Loop…” ;)

2Jeff Starr

September 3, 2008 at 1:57 pm

Thanks for the catch, Erika — fixed!! :)

3Simon

September 5, 2008 at 8:04 am

Hey congrats on making the 9rules list, it’s great to see your blog in there. Pity though you closed the htaccess for comments, I think it’s a great post, just can’t get this thing to work properly though..Cheers Simon

4Jeff Starr

September 6, 2008 at 3:34 pm

Hi Simon, thanks for the congrats! I am looking forward to supporting the 9rules network. I am honored to be a part of it. As for the htaccess comments, I can only assume that you are referring to my article, “Stupid htaccess Tricks.” If so, yes, I was getting a ton of “drive-by” support questions that were really draining my time from more critical pursuits. Although there are many other htaccess posts from which to learn, I am also available for hire through my design site, Monzilla Media. In any case, thanks for dropping by — I appreciate the feedback! :)

5Simon

September 7, 2008 at 1:51 am

Haha I thought so that it was getting too intensive there. Yeah in any case keep it up!

6Binh Nguyen

September 23, 2008 at 12:14 pm

Thanks for this article. It’s a good idea to have many loops. I really am interested in knowing how to get different loops based on categories, not offset.

Any idea?

7Jeff Starr

September 24, 2008 at 11:18 am

Hi Binh, to implement different loops based on categories, you can use the general techniques described in this article along with any number of category parameters. Simply modify your set of query_posts loops with the desired category parameters and full control is yours.

8Binh Nguyen

September 24, 2008 at 11:28 am

Thanks Jeff Starr for your great tip. Now I know out how to do it.

9Jeff Starr

September 24, 2008 at 11:38 am

My pleasure, Binh — happy to help! :)

10Donace

October 2, 2008 at 8:28 am

very useful post man, filed it away for when I have the time to work on a new (my first) theme.

11Jeff Starr

October 5, 2008 at 10:39 am

Thanks for dropping by, Donace — it’s great to see you again! :)

12damir - SEO Tips

October 15, 2008 at 11:36 am

Man, you are the king! I have been bookmarking many of your posts cause I like to customize my themes and every loop and trick you give, works awesome. I have found some other sites that offer codes and different loops but a lot of them just don’t work. Thank you.

13Jeff Starr

October 19, 2008 at 2:54 pm

My pleasure, damir — thanks for the positive feedback! :)

14nazerry

October 25, 2008 at 12:20 am

dear jeff,

i’ve tried this method on xampp, and it works. but the problem is when i click the next page, it displayed the same post in the first page. can you help me out here?

thanks..

15LuisRaa

October 26, 2008 at 1:30 pm

Hi Jeff:

i need to develop a website with posts in two columns (the center column and a sidebar column for certain categories) but i need to limit the words in the sidebar posts to mantain the design, i’ve try with the excerpt, but this limit to a few words and no apply to images, there is a code you can bring me to make this?

Im running 2 loops with diferent queries and i need help on this

thanks in advance

regards

16Jeff Starr

October 29, 2008 at 4:11 pm

@LuisRaa: Have you looked into using the excellent Excerpt Reloaded plugin..? With it, you can configure just about anything you need, including excerpt length, type, format, and much more..

17nazerry

November 2, 2008 at 5:15 am

hi jeff, can u solve the paging problem?

18Jeff Starr

November 2, 2008 at 9:10 am

@nazerry: ..and which paging problem might that be..? If you are referring to the infamous next_posts_link and previous_posts_link paging problem, I would recommend a thorough search on Google. The issue is very problematic for many people and I have only discovered temporary workarounds that I cannot recommend to the public..

19Viidar

November 4, 2008 at 9:03 am

Very nice and informative!
Will definitely use this on the theme I am working on now!
Thanx!

20davebach

November 12, 2008 at 9:35 pm

Great article… just what I’m looking for. I keep coming back to your site to learn a thing or two or three. I modified your complete code above to display excerpts and images for a category page I have (I’m going for a “grid” view). In comment #7 above, you suggest to Binh to modify query_posts() with the category parameters. I want to do the same thing, but I can’t seem to get it to work. I changed it to read query_posts(’cat=13&showposts=5′) but it still shows the last 15 posts of all categories.

What might I be doing wrong?

21Muffin

November 13, 2008 at 3:41 am

I want to do the same thing with a category template. How can I do this? cause right now it won’t show posts from that particular category

22Jeff Starr

November 17, 2008 at 9:33 am

@davebach, @Muffin: Perfect timing for both of you! I was getting so many requests for category-specific loop filtering that I just didn’t have time for them all, so I decided to write up a complete tutorial covering the entire process:

Fruit Loop: Separate any Number of Odd and Even Posts from any Category in WordPress

Fresh out the oven — posted earlier today! Enjoy :)

23Paul Demers

November 18, 2008 at 7:14 am

Thanks so much for this tutorial. I am just starting to really dig into Wordpress and this was a very clear explanation of a fundamental concept. Adding this site to my feedreader as we speak.

-Paul

24davebach

November 18, 2008 at 7:31 am

@ Jeff RE: davebach and muffin:

Thanks Jeff, Fruit Loops is another fine tutorial… what I ended up doing to the example you give in this post (so that I can achieve a three column “grid view” using excerpts… follow link above to see) is I added “cat=” to both query_posts and get_posts in each loop. This gave me the result I wanted, however I had to reduce the count to 4 per column because I (currently) have only 12 posts in that category… if it kept looking for more posts than I had it would give an error.

At some point I’d like to figure out how to get this into 4 columns (or rows of 4 across so that it reads newest to oldest… but I’m still learning the finer points of CSS and I couldn’t get it to look right with 4 excerpts, line break, 4 excerpts, line break, etc.)

Dave

25Jeff Starr

November 18, 2008 at 9:00 am

@Paul Demers: Great to hear, Paul! I look forward to sharing new WordPress articles with you! Welcome aboard! :)

@davebach: Good point about specifying post numbers that take into account the total overall number of posts. This is a very important point that catches many of us by surprise. Also, thanks for mentioning the chronological 4-column excerpt layout.. I like the idea and will try to fashion a solid tutorial on the subject within the next couple of weeks. Thanks for the idea! :)

Subscribe to comments on this post


Share your thoughts..

TopRead official comment policy

Contact Perishable Press

  • Contact Jeff via form

Search Perishable Press

About Perishable Press

Perishable Press is the virtual playground of Jeff Starr — visionary, founder and lead developer of Monzilla Media, a small web and graphic design company in the lush desert oasis of Moses Lake, Washington. Perishable Press features articles and tutorials on many aspects of digital design..

Read more..

Perishable on Twitter

better to have too many ideas and not enough time than the converse

Perishable on Tumblr

WordPress Tip for Multiple Themes

Sunday, 4 January 2009, 5:16 pm

If your site makes available multiple themes for users to choose from, remember to include the JavaScript (or any other required code) for any statistical applications that you might be using, such as Mint, Google Analytics, and so forth. I am not sure about the various WordPress statistics plugins, but they may need to be included as well. A good way to check if your stats plugin is tracking data across all themes is to either visit a few pages that you know others aren’t hitting, or else activate each of the alternate themes and check the source code of each one for the required code.

Earlier today, I realized that only several of my most recent themes included the required JavaScript for Mint and Google Analytics. I am now in the process of editing each of the 18 themes available for users at Perishable Press. Haven’t decided on whether or not both statistics apps are needed for all themes, but I will certainly be using at least one of them to keep an eye on everything.

Insane Christmas

Monday, 22 December 2008, 9:47 pm

For as long as I can remember, Christmas has always been a relatively peaceful affair. Sure there’s the usual holiday stress — traffic, shopping, presents, relatives, and all that goes with the preparation of a traditional celebration, but when it’s all said and done, you get to relax and enjoy the peace and harmony of gathering together and basking in the reason for the season: the birth of Christ.

This year, however, the stress factor has been kicked up a few notches, making for a rather insane Christmas if I do say so myself. In addition to the usual holiday chaos, we are currently purchasing a brand new home, and quickly realizing the incredible amount of work involved in the process. If you’ve ever bought a newly built home, you know exactly what I am talking about here.

Plus, as if all the paperwork, inspections, insurance, costs, and anxious anticipation weren’t enough to confound the usual holiday stress, we are also packing up everything, dealing with kids, working full-time jobs, and — beginning on Christmas Eve — moving into our new house.

It certainly is all a great joy and blessing to have such amazing things going on, but combined with the work that I do on the Web — blogging, designing, projects, helping people, and so on — it really becomes all too much rather quickly. We are doing are best to get through everything with our sanity intact, but I have to admit that this is the most insane Christmas I have ever experienced.

New (4G) Blacklist Now in Beta

Monday, 22 December 2008, 9:27 pm

Just a quick note to anyone interested in securing their websites against malicious activity, spam, and other nonsense. Several months after releasing my 3G Blacklist, I have finally begun work on the next incarnation of the blacklist: the 4G Firewall!

The first part of the blacklist is now ready for testing, and I plan on setting it up on Perishable Press within the next few days. While testing on my own site, I thought it would beneficial to also invite a few “beta” testers to run the code on their own site(s) as well.

So, if you have a site that receives its share of malicious attacks, and cracker exploits, drop me a line via the contact form at Perishable Press and I will send you the initial block of HTAccess directives. This version of the Blacklist is looking better than ever, and I look forward to releasing the complete version to the public early in 2009.

Thanks for the Free Traffic and Link Juice

Sunday, 7 December 2008, 1:26 pm

Just wanted to thank the fine folks at fafich.ufmg.br for all the free traffic and link juice. Thanks to their misapplication of my comprehensive canonicalization code, every non-canonical version of their 21,700 indexed pages points directly to my site, Perishable Press. This means that every one of their permalink URLs that is mistyped, lacks the “www” prefix, or contains the superfluous “index.php” file name is directed via permanent redirect directly to the home page of my site.

I have tried contacting the site owner(s) about this situation, but it has been over a week and I have yet to hear anything back. Hopefully, they will take notice soon and correct the issue by properly configuring their htaccess file, but in the meantime, I certainly don’t mind the extra link juice and free traffic! :)

No Plugin Needed for Feed Delay

Monday, 24 November 2008, 10:01 am

I recently saw a WordPress plugin that was designed to delay the publication of your WordPress feed by any specified time interval. While it is a good idea to carefully proofread your content before posting it, a plugin certainly is not required to do so.

As savvy WordPress users already know, WordPress has a built-in post-preview feature that enables authors to view their unpublished content as a published post. This enables authors to do any amount of proofreading and browser checking until they are satisfied with the results.

To do this, simply write your post as usual, and then click on the “Preview this post” button on the right-hand side of the screen. In older versions of WordPress (less than 2.5, I think), you actually need to save (without publishing!) the post first and then re-open it as if to continue editing. You will then see a “Preview »” link sort of hidden (due to poor CSS design) in the upper-right corner near the edit post field. Right-click on that link to open in new tab and you are good to go.

No extra plugin needed! :)

Read more on Tumblr..

Subscribe to Comments Recent Dialogue

  • Jeff Starr: Hi heywho, glad to hear you are doing well! ;) I wish I could join in the festivities.. it has been so long that I almost have forgot...
  • Rob Barrett: Thanks for posting about the Stealth Publish plugin -- just what I needed for my site. Works perfectly!...
  • Jeff Starr: Hi Chiwan, I got your email and have sent some information that may help you with this. Cheers, Jeff...
  • Chiwan: Hi. This is cool. So I can I replace the clock that comes with your Apathy theme with this clock? If that's not possible, how do ...
  • Brass Engraved: Thankyou very much for this, worked like a dream!...
  • Patrix: I'm using FeedBurner and the Feedsmith plugin for my filter blog, DesiPundit. I found your post via the WordPress page for RSS feeds ...
  • teddY: @Jessi Hance: Sorry to hear about your experience with Twitter spammers/flamers. I was once a victim of flamers and it sucks that peo...
  • heywho: Hey.... Very Nice...... I'm TOTALLY not a programmer..... but I have this thing I want to do...... so I just decided to start doi...
  • Rodrigo Nunes: NIce SEE MY BLOG http://designrn.wordpress.com/...
  • zubfatal: The Quintessential theme looks great to me, however when scrolling up or down on the page, it makes my laptop work harder than it sho...

Read more recent comments..

Attention: Do NOT follow this link!