How to stop post duplication when using multiple WP_Query() requests

Filed February 12th, 2012 under Tutorial and WordPress

On my site SalaciousSound I have two selections of articles: five ‘featured’ posts which appear at the top of my index, above the fold, and ten more of my most recent articles.

I wanted to exclude the featured articles from appearing in the regular articles section, and I did so by using the WP_Query() parameter ‘post__not_in’.

The reason for writing this article is that collecting the post IDs from my first WP_Query and passing them to the second was, for me, non-trivial because the five featured articles appear in my header.php file and the ten regular articles appear in index.php.

In order to achieve my desired result I had to set a php variable in my functions.php file, and then declare it as a global variable in my header.php file and index.php file.

Here’s how the relevant code looks:

from functions.php
$featIDs = array();
from header.php
global $featIDs;
$feats_query = new WP_Query('category_name=Features&posts_per_page=5');
while ($feats_query->have_posts()) : $feats_query->the_post();
	array_push($featIDs, $post->ID);
from index.php
global $featIDs;
$index_query = new WP_Query(array(
	'posts_per_page' => 10,
	'post__not_in' => $featIDs
));
Cailen
Cailen lives in Toronto. He is passionate about music and coffee culture, photography and videography, and code efficiency.

2 Responses

§ Chris wrote on March, 1st:

Just the piece of code I was looking for. I’d tried using the offset feature but this doesn’t play nicely with pagination. Thanks for the solution.

§ Cailen McQuattie wrote on March, 5th:

No sweat!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>