I’ve been meaning to write up some of my WordPress-fu since I started playing with it. This is partly because the WordPress support forums are staggeringly unhelpful at times, especially to medium-skill users. (Note: this is not a flame or a troll; it is an issue I will return to at a later date. Whilst I like the product, I have several worries and issues with the community around it).
This is about the first big chunk of fiddling I did with WordPress, and makes it very useful as a more general purpose CMS, as well as if you have many categories on your site and want to display them all, at once, differently. So, without further ado: how to display multiple loops in WordPress 1.5.
“The Loop”, in the parlance of WordPress, is your main piece of syntax for display posts. The Loop basically says “if there are posts, display each post in the following manner“. In 1.5, they made WordPress behave more in the manner of an if/while…do statement, which is actually a much clearer way of understanding it than the old method.
Now, not everyone wants to display all their posts at once – some are in inappropriate categories. It’s very easy to display posts from a single category with an
if statement. But what if you want to have multiple loops on one index page – say, for instance, if you have a magazine in sections and want to show the latest post in each category on your front page?
It’s not so hard. The trick to having multiple loops is to realise that you need to re-set the query string that each loop runs, for each loop on the page. Best explained with some code:
<?php query_posts('category_name=CatName&showposts=1'); ?>
<?php while (have_posts()) : the_post(); ?>
<i>Your display code goes here</i>
<?php endwhile; ?>
Essentially, you force the query string to show you 1 post from category CatName. Then you put in a loop as shown above (note no
if statement). It’ll display that one, latest post however you have formatted your display code.
What’s nifty is if you then repeat this chunk of code, but say, with a different CatName, you’ll get the top post in that category appearing when the loop runs – because you’re now running a different query. You’re not limited to 1 at a time, either; you can use it to display any number of posts. There’s a lot you can do, as I’ll show in a few more pieces like this, by manually overriding the query string to suit your needs.
As you can see, WordPress stops being a nice little weblog engine and suddenly becomes a very useful general purpose CMS; you can write index pages with more than one loop, and categorise your content very effectively (of course, this works best with posts that are only in one category).
I hope that’s been of use. Next up in this series : how to code “more like this” statements to show you recent posts in a category and recent posts by an author.