Skip to content


WordPress: multi-loop

In a previous post, I looked at The Loop in WordPress and how it was possible to exclude specific categories from being displayed. I did that to exclude posts from my Web category as I wanted them handled differently.

This time around, I’m going to retrieve and display posts without going into The Loop. To do this, I’m going to create a secondary loop with the get_posts template tag.

At the simplest level, you could use this to create a sticky post (though as of version 2.7, WordPress does this without any additional coding). By playing around with this, you could create a multi-loop, multi-column theme that completely changes the way a blog looks.

I’m going to use get_posts to retrieve and display posts from the category I previously excluded from The Loop. To do so, I’m going to drop the following code in the left sidebar template file of my blog theme:
< ?php $lastposts = get_posts('cat=6&numberposts=5'); foreach($lastposts as $post) : setup_postdata($post); ?>
< ?php the_content(); ?>

< ?php endforeach; ?>

That tells WordPress to retrieve and display the contents of the last five posts in category 6 (i.e. the “Web” category) in the left sidebar. Note that this will merely get the post content and completely ignore post meta data (e.g. post title, date published, author name, etc.).

You could drop that code anywhere: the left sidebar, the right sidebar or the bottom of the main column (outside of The Loop, naturally) and it would accomplish the same thing.

The other neat thing about this is you could call any number of posts from the category by simply changing the “numberposts” value.

There are other methods of implementing asides like that on a WordPress blog.

You could use the Sideblog plugin. I’ve had some trouble with version 5.1 and had to revert to 4.5 on another blog but it may work for you.

You could also resort to an external application. For instance, Twitter in combination with the Twitter Tools plugin. The downside is you’d have to work around Twitter’s silly 140-character limit and the inelegant way it handles URLs.

Posted in WordPress.


2 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Pascal says

    Hey there, thanks for this post! It helped me a lot in dealin’ with a multiple-loop problem ^^

Continuing the Discussion

  1. WordPress: Categorically speaking : Fuyoh! linked to this post on Sunday, May 17, 2009

    […] previous posts, I looked at excluding a category from the main page of WordPress blog and displaying posts from a […]