How to stop post duplication when using multiple WP_Query() requests
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 ));