4/13/2008 ↓

Define Your Own WordPress Loop Using WP_Query

Author: Ronald Huereca Category: HOW-TO, WordPress Hack

Thanks for visiting! If you're new here, you may want to subscribe to our RSS feed. This blog posts regular Wordpress news, updates of themes, plugins, ideas, hacks, quick fixes and everything about blogging, especially about Wordpress. Go ahead, subscribe to our feed! You can also receive updates from this blog via email.

We all know what the WordPress Loop is right? If not, there are many great tutorials around the web that explain the WordPress Loop.

One of the easiest ways to navigate and manipulate the loop is to use the function called query_posts. Nathan Rice calls it a WordPress developers best friend.

When you use query_posts, however, you risk the following:

  • Potential to interfere with plugins which make use of the Loop.
  • Potential to invalidate WordPress conditional tags.
  • Having to deal with resetting, rewinding, offsetting…

I say skip query_posts. In a way you’ll still be using it, but the better (and sometimes easier) technique is to instantiate your own WP_Query object and create your own loop.

Creating Your Own Loop With WP_Query

The first step is to instantiate your own variable using the WP_Query class.

What we’ll be doing in this example is creating a common feature on blogs, which is to display a list of the recent articles.

<?php
    $recentPosts = new WP_Query();
    $recentPosts->query('showposts=5');
?>

All I’ve done in the above code is defined a variable named recentPosts and instantiated an instance of WP_Query.

I then used a method of WP_Query to start a query (pretty much the same thing as using query_posts). You even use the same usage parameters as query_posts.

Now it’s time to start our own loop:

<?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>
   <!-- do some stuff here -->
<?php endwhile; ?>

Notice the use of the recentPosts variable to start the loop. We utilize two methods of WP_Query, which is have_posts and the_post. You can read more about those two methods on my article Global Variables and the WordPress Loop.

The beauty of this is that once you are inside your own loop, you can use the standard post tags.

The Full Code

Here’s the full code for showing the last five recent posts using your own loop:

<h3>Recent Articles</h3>
<ul>
<?php
    $recentPosts = new WP_Query();
    $recentPosts->query('showposts=5');
?>
<?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>
    <li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>

Update: Using Pagination

This comment is from Aaron Harun -

@Ron and Monika

If you use the query:

$recentPosts->query('showposts=5'.'&paged='.$paged);

it will automatically page the wury based on the page number passed
through the url eg "/page/4"

However, this doesn't work with the “post_nav_link” function because it
only checks the $wp_query variable. To get around this you have to
trick the function by switching $wp_query on it. Add the first block
before your custom loop and the second after to achieve this effect.

<?php //query_posts('paged='.$paged);
$temp = $wp_query;
$wp_query= null;
   $wp_query = new WP_Query();
   $wp_query->query('showposts=5'.'&paged='.$paged);
?>

<?php $wp_query = null; $wp_query = $temp;?>

Thanks Aaron for the contribution.

Conclusion

Defining your own loop using WP_Query is an easy way to run your own custom queries without interfering with the default Loop. It’s also a great way to run multiple loops that are completely independent of each other.

WordPress Resources mentioned:

1 Star2 Stars3 Stars4 Stars5 Stars (8 votes, average: 4.75 out of 5)
Loading ... Loading ...
Sphere: Related Content | stumbleit |
Translate to German Translate to Spanish Translate to French Translate to Italian Translate to Portuguese Translate to Japanese Translate to Korean Translate to Russian Translate to Chinese

Latest Videos

Latest WordPress Jobs

32 Comments | Leave a comment | Comments RSS

  1. Hi Ronald
    I have a great wish:
    This way is killing the next and previous link. Please show this loop with full functionable pagination or “thousands” ;) of support threads will be open….pagination doesn’t work for me

    thanks a lot
    Monika

    Monika (33 comments.) — 04/13/2008 @ 4:43 am
  2. Monika,
    I’m afraid I don’t know the answer to that. It looks like from the pagination code that it ties into the default loop.

    It appears that you’ve found a weakness of this technique over query_posts. To be honest, I don’t think you’d really want to use pagination with this type of technique, which should be independent of the standard WordPress loop.

    Perhaps someone else can chime in?

    Ronald Huereca (65 comments.) — 04/13/2008 @ 4:57 am
  3. Hi Ronald

    To use this loop in index.php doesn’t make sense, so I try it in archive.php , WP has the order to show 10 articles per page,

    with this loop it shows 5 recent posts and 5 from the archive, because to combine two loops with if have posts …while … WP dig one’s heel in and says: 10 articles are 10 articles ;)

    I have this day no time to play with your loop, but if someone would like to us it he must be aware of this ;)

    kindly regards

    Monika

    Monika — 04/13/2008 @ 7:05 am
  4. I’ve used this method for the index page to separate a featured post:


    $my_query = new WP_Query('cat=-1&showposts=1');
    while ($my_query->have_posts()) : $my_query->the_post();
    $do_not_duplicate = $post->ID;

    ... do stuff here ...

    endwhile;

    and further down show the rest of the posts

    if (have_posts()) : while (have_posts()) : the_post();
    if( $post->ID == $do_not_duplicate ) continue; update_post_caches($posts);

    .. do stuff here ...

    endwhile;

    ...pagination...

    else;
    endif;

    The only way that I could get pagination to work was to remove one category from showing…so I chose the default uncategorized category. Since I wanted every post being under a category that I defined, it really wasn’t an issue.

    Darryl (6 comments.) — 04/13/2008 @ 8:35 am
  5. I forgot to mention that with this I was also using WP-Sticky to “sticky” the featured post (sticky for single day, announcement for multiple days). Without this plugin it would just show the latest post in the featured post area.

    Darryl (6 comments.) — 04/13/2008 @ 8:54 am
  6. @Monika: Thanks for that technique. I was wondering a more effective way to separate a featured post from the rest of the loop.

    Leland (8 comments.) — 04/13/2008 @ 9:07 am
  7. oh there was a fatal error if I tried to send my comments before , so I’ll try it again

    @ Leland there is no loop from me in this comments

    I know 5 ways to highlight the first post
    http://www.texto.de/texto/5-wa.....ess-theme/

    and here is my loop for the last 5 posts with pagination

    OH! it is my code I’ll try it in another way


    Recent Articles

    rewind_posts();
    $wp_query->query_vars["showposts"] = 5;
    $wp_query->get_posts();
    if (have_posts()) : while (have_posts()) : the_post(); ?>
    …your stuff


    endwhile;

    …next_posts_link(’« Older Entries’) …
    .. previous_posts_link(’Newer Entries »’) ….


    endif;

    regards Monika

    Monika — 04/13/2008 @ 9:43 am
  8. [...] ????? Define Your Own WordPress Loop Using WP_Query?????? [...]

  9. Ronald,
    You’re absolutely right. query_posts kills your other loops (if using multiple loops). I’ve been using the alternate technique for about 6 months now, and it works great!

    And as far as I know, pagination only works with the default loop. It’s best to use conditional tags to qualify the standard loop if you want to keep pagination. For instance, if you want to exclude a category from the standard loop, then do this:

    if have posts : while have posts : the post
    if(!in_category(’2′)) :
    standard stuff like title and content
    endif
    endwhile
    endif

    That excludes any post that is in category 2 from being displayed. Pretty easy.

    Nathan Rice (8 comments.) — 04/13/2008 @ 11:53 am
  10. Thank you for the guide!

    Thaya Kareeson (7 comments.) — 04/13/2008 @ 3:00 pm
  11. Thanks everyone for their input. I’ve amended the post with some further input.
    Ronald Huereca (65 comments.) — 04/13/2008 @ 4:09 pm
  12. [...] The technique I use makes use of two custom functions placed in a theme’s “functions.php” and a custom WordPress Loop. [...]

  13. [...] Define Your Own WordPress Loop Using WP_Query ** Posted using Viigo: Mobile RSS, Sports, Current Events and more ** We all know what the WordPress Loop is right? If not, there are many great tutorials around the web that explain the WordPress Loop. [...]

  14. [...] Weblog Tools Collection » Blog Archive » Define Your Own WordPress Loop Using WP_Query (tags: wordpress loop wp_query php theme blogging development howto) [...]

  15. Thanks, Ronald. This was really helpful. Is there any chance you could go into more detail about how the pagination workaround works?

    Julian Johannesen — 04/14/2008 @ 12:38 am
  16. [...] Define Your Own WordPress Loop Using WP_Query (tags: wordpress) [...]

  17. [...] Weblog Tools Collection » Blog Archive » Define Your Own WordPress Loop Using WP_Query Så simpelt, så simpelt. Dette kan jeg bruge mange steder, hvor wp_query kommer i konflikt med noget andet. (tags: wordpress loop wp_query howto tutorial)   [...]

  18. [...] Define Your Own WordPress Loop Using WP_Query - WTC Så gör du en alternativ loop i dina Wordpress-mallar. (tags: wordpress loop php theme howto) [...]

  19. Great and informative post. I’ve been learning and modifying the loop myself by following other tutorials, this is a great addition. Like Julian above, I would like to learn more about the pagination workaround though. It seems like a really great feature, especially if a page has many different loops running. Paging results seems like a really great user experience.

    WP Modder (1 comments.) — 04/15/2008 @ 11:31 am
  20. @Julian, WP Modder,
    That would probably require a separate post for the explanation. I’ll see what I can do.
    Ronald Huereca (65 comments.) — 04/15/2008 @ 12:44 pm
  21. [...] Weblog Tools Collections, come creare il proprio loop WordPress e visualizzare solo alcuni post in base ai valori dei custom [...]

  22. [...] Define Your Own WordPress Loop Using WP_Query (tags: wordpress code php) [...]

  23. Thank you! Good guide and a perfect way to run multiple independent loops.

    Herbert (1 comments.) — 04/19/2008 @ 2:01 pm
  24. [...] from this blog via email.Last week I published two articles using custom loops. The first was about how to create a custom loop. The second was how to retrieve posts based on custom fields. In both articles, several readers [...]

  25. [...] un peu plus votre blog. De la même trempe que celui présenté au dessus, ici, on vous propose de créer une boucle Wordpress entièrement grâce aux Query Posts et de récupérer des articles via les champs personnalisés de Wordpress, les fameux “Custom [...]

  26. [...] Weblog Tools Collection » Blog Archive » Define Your Own WordPress Loop Using WP_Query (tags: wordpress) [...]

  27. [...] Weblog Tools Collection » Blog Archive » Define Your Own WordPress Loop Using WP_Query (tags: wordpress php wp_query tutorial theme) [...]

  28. [...] Weblog Tools Collections, how to create your own WordPress loop and how to retrieve posts based upon custom fields [...]

  29. I use this on my site for the listing of posts on the main page, with two wp_query loops on the right side of the page. Then in my sidebar (left side) I use it for the quick thoughts (or asides as everyone calls them), the latest gallery and latest panoramic image.

    So all in all when you view the main page of my Web site, that is five wp_query post loops.

    Tim Wheatley (1 comments.) — 05/4/2008 @ 11:58 pm
  30. [...] Define Your Own WordPress Loop Using WP_Query [...]

  31. [...] ????? Define Your Own WordPress Loop Using WP_Query????? [...]

  32. How to fetch posts based on custom fields. I want to show posts that contain similar custom field value, using WP loop (so that pagination work).

    Kashif (1 comments.) — 07/3/2008 @ 7:04 am

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

(required)

(required, will not be published)


S2