WordPress Snippet: Display multiple loops on the same page

Let’s say that on a category page of your WordPress blog, you want to display a secondary list of posts, for example the 3 latest posts from a “featured” category.

You have a couple of good options here:
1. create a new WP_Query object, or
2. use the get_posts() function.

Note: Using query_posts() is a bad option as it will upset your “main loop”

Both take pretty much the same arguments as query_posts() – see a list here.

Example usage of WP_Query:

$featured_category_id = 10;
$args = array('posts_per_page'=>3, 'cat'=>$featured_category_id);
$query = new WP_Query($args);
 
while ($query->have_posts()) : $query->the_post();
	the_title('<h3>', '</h3>');
endwhile;

Example usage of get_posts():

$featured_category_id = 10;
$args = array('numberposts'=>3, 'cat'=>$featured_category_id);
 
foreach (get_posts($args) as $post):
	the_title('<h3>', '</h3>');
endforeach;

Comments are closed.