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.
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
That’s pretty cool. Would work great on Magazine style sites if one has to build a theme from scratch.
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!
Awesome! I could change some of the code so that it shows a featued post instead
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]
Ignore the previous comment, sorry, forgot the code wouldn’t post!
Is it possible to make a loop that show’s posts of the same week/month from the year before?
@derFrankie: Sure it is. It’s a good idea, so I’ll write a recipe about that soon. Stay tuned!
@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/
Thanks for the link! I don’t understand any German, but the code is nice
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)
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!
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: