Avinash asked “How to use two different WordPress loops?”

One of my readers, Avinash, asked how he can create two distinct WordPress loops on the same page. Avinash wants to get the most recent posts first, and later create a new loops getting the 5 next posts, excluding the most recent post.

To achieve what Avinash wants to do, we have to use the query_posts() function with the showposts and offset parameters.

The first loop:

query_posts('showposts=1'); // First loop, we only get the most recent post
if (have_posts()) :
     while (have_posts()) : the_post(); ?>
         // WordPress loop
     endwhile;
endif; ?>

The second loop:

query_posts('showposts=5&offset=1'); // Second loop, we get 5 posts excluding the most recent.
if (have_posts()) :
     while (have_posts()) : the_post(); ?>
         // WordPress loop
     endwhile;
endif; ?>

A little explanation about query_posts() parameters we used here:
showposts=5 specifies that you only wants to get 5 posts.
offset=1 specifies that you don't want to get the 1st most recent post.

16 Responses

Oct 27 2008 17:21

That’s pretty cool. Would work great on Magazine style sites if one has to build a theme from scratch.

Oct 27 2008 17:50

Exactly! Most magazine themes uses more than one loop per page, so it’s always a good thing to know how to run a second loops without getting the posts you already displayed!

Oct 28 2008 00:50

Awesome! I could change some of the code so that it shows a featued post instead :)

Oct 31 2008 21:03

Can anyone spot anything obviously wrong with the following? I haven’t used query_posts before and I’m trying to use it in my photos category.

[code]

endwhile;
endif; ?>

2007

endwhile;
endif; ?>
[/code]

Oct 31 2008 21:04

Ignore the previous comment, sorry, forgot the code wouldn’t post!

Nov 07 2008 13:44

Is it possible to make a loop that show’s posts of the same week/month from the year before?

Nov 07 2008 13:54

@derFrankie: Sure it is. It’s a good idea, so I’ll write a recipe about that soon. Stay tuned!

Nov 07 2008 16:21

@jbj – Cool, I will stay tuned

I found also on another blog a tipp for “future” post display

http://wp-magazin.ch/2008/11/07/den-leser-in-die-zukunft-blicken-lassen/

Nov 07 2008 16:58

Thanks for the link! I don’t understand any German, but the code is nice :)

Jan 26 2009 02:36

Thank-you so much!!!

I run a Big Brother magazine style website and this has made it possible for me to have a “top Story”. Thank-you so much!

Alec (UK)

Jun 04 2009 20:32

Wow! This was super helpful and easy to use! I plugged the code in on a new blog I’m working on – http://www.wenatcheefitnessblog.com and it worked great!

Thanks!

Jan 18 2010 17:45

I’m trying to show sticky page content at the top of the page and posts below which I assume would require usage of the loop twice. How would I do this using this example? Thanks for your help! Christian

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required