Remove Duplicate Posts from Custom WordPress Loop

Posted on Tuesday, January 14th, 2014

How to: WordPress Remove Duplicate Posts Loop

In WordPress, sometimes you want to run multiple custom queries, but you don’t want the same post to appear in each query. This can happen when you want to feature posts in different categories, but a post may exist in multiple categories, so it is possible for the post to appear under each category.

This article describes the proper way to remove duplicate posts from multiple queries, so that the proper number of posts appear, and the same post won’t appear multiple times.

Find the file you want to edit, and before your custom query, declare a new variable:

/** This is where we are going to store the post ID's for the posts we've already displayed
 * Note: this resets the variable, so be sure to only include it once.
 * Also, if it's included in a template part, beware it may get called multiple
 * times, which would allow posts to be duplicated
 **/
$do_not_duplicate = array();

Then, inside your loop, add each post ID to the $do_not_duplicate variable:

$query = new WP_Query($args);
if ($query->have_posts()) {
    while($query->have_posts()) {
        // Add the post ID to the array
        $do_not_duplicate[] = get_the_ID();

        // Your code to display the post goes here...
    }
}

Finally, to bring it all together, when you are preparing your next custom query arguments, pass in the array into the post__not_in parameter, like so:

$args = array (
    'post_type'        =>  'post',
    'posts_per_page'   => '10',
    'post__not_in'     => $do_not_duplicate
);
$query = new WP_Query($args);

And there you have it! The posts from the second custom loop will not include any duplicates from the first post.

And, you can string this together for multiple custom queries. Just keep adding post ID’s to the variable, and using the post__not_in parameter, and you will be all set. (Note: do not put the first line in the code again, otherwise it will reset the variable, and you will begin getting duplicates again! This line: $do_not_duplicate = array(); resets the variable, so only declare this once at the top of the file).

One Response to Remove Duplicate Posts from Custom WordPress Loop

  1. Sandy says:

    Thanks for the post, I was able to understand your explanation. I did not know there was a post__not_in, I used it in my array merge.

    It helped me! thanks!

Leave a Reply

(required)

comment on this post »

1 comment on this post

Sandy:  “Thanks for the post, I was able to understand your explanation. I did not know there was a post__not_in, I used it in my array merge. It helped me! thanks!”June 5, 2014 | 12:21 am