We all know what the
One of the easiest ways to navigate and manipulate the loop is touse the function called
When you use
- Potential to interfere with plugins which make use of theLoop.
- Potential to invalidate WordPress conditional tags.
- Having to deal with resetting, rewinding, offsetting…
I say skip
Creating Your Own Loop With WP_Query
The first step is to instantiate your own variable using theWP_Query class.
What we’ll be doing in this example is creating a common feature onblogs, 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 variablenamed
I then used a method of
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
The beauty of this is that once you are inside your own loop, youcan use the
The Full Code
Here’s the full code for showing the last five recent posts usingyour 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
@Ron and Monika
If you use the query:
$recentPosts->query('showposts=5'.'&paged='.$paged);
it will automatically page the wury based on the page numberpassed
through the url eg “/page/4″
However, this doesn’t work with the“post_nav_link” function because it
only checks the $wp_query
trick the function by switching$wp_query
before your custom loop and the second after to achieve thiseffect.
<?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 yourown custom queries without interfering with the default Loop. It’salso a great way to run multiple loops that are completelyindependent of each other.
WordPress Resources mentioned: