April 13th, 2008
Define Your Own WordPress Loop Using WP_Query
We all know what the is right? If not, there are many great tutorials around the web that .
One of the easiest ways to navigate and manipulate the loop is to use the function called . calls it .
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 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 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 .
The beauty of this is that once you are inside your own loop, you can use the .
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>
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:
Related CMS news:
Leave a Reply