SJL Web Design

Display Posts Outside the WordPress Loop

There are two ways to pull content from outside the WordPress loop (the right way and the wrong way). One of these ways (the wrong way) is to use the query_posts() function to retrieve the content from outside the loop. However, WordPress does not recommend this method as it can interfere with the main loop, you can read what they have written about it below:

The query_posts() function is intended to be used to modify the main page Loop only. It is not intended as a means to create secondary Loops on the page.

If you want to create separate Loops outside of the main one, you should create separate WP_Query() objects and use those instead.

Use of query_posts() on Loops other than the main one can result in your main Loop becoming incorrect and possibly displaying things that you were not expecting.

This leaves us with the second option (the right way), which is to replace query_posts() with the WP_Query() function as mentioned above.

Using the WP_Query() function

Our first step will be to setup the query by initiating our own variable using the WP_Query class.

$latestPosts = new WP_Query();

This will pull our 5 most recent posts, you can change the parameters within the variable to suit your needs – you can find a full list of parameters here.

Once we have created the query we are now going to need to setup the loop to display the posts. Here is a basic example of how it will start off looking:

while ($latestPosts->have_posts()) : $latestPosts->the_post(); ?>
     (content goes here)
<?php endwhile; ?>

So when we put all of this together it should look something like:

<h3>Latest Posts</h3>
    $latestPosts = new WP_Query();
<?php while ($latestPosts->have_posts()) : $latestPosts->the_post(); ?>
    <li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile; ?>

Leave a Reply