DISCLAIMER: this post is older than one year and may not be up to date with latest WordPress version.

Today, my friend Mehmet asked me if I know how to use multiples loops without having the duplicate posts problem. There’s probably many other ways to achieve the same effect, but here’s a pretty nice way to avoid duplicate posts in two or more loops.

To avoid post duplication, I started by creating a php array, and adding the IDs of the posts I get in the first loop to that array:

<h2>Loop n°1</h2>
$ids = array();
while (have_posts()) : the_post();
<br />

<?php $ids[]= $post->ID;
endwhile; ?>

Now, the second loop: I have used the php function in_array() to check out if a post ID is contained in the $ids array. If the IDs isn’t contained in the array, we can display the post as it wasn’t displayed on the first loop.

<h2>Loop n°2</h2>
while (have_posts()) : the_post();
if (!in_array($post->ID, $ids)) {
  <br />
<?php }
endwhile; ?>

That’s done: No duplicated post!
Alternatively, it is possible to transform the $ids array to a comma separated string and use in along with the exclude parameter of the query_post() function.


  1. Thanks for this short but extremely useful post. I’m implementing it now on a new project.

  2. Thanks for the tip!! I’ve just have one question, I am a novice wp developer but is not better use the funcition “post__not_in…” ? Whats the difference?

  3. Alternatively you second and any loop following could look like this:

    Loop n°2
    ’20’, ‘post__not_in’ => $ids ) );
    while ( have_posts() ) : the_post();

    endwhile; ?>

  4. I’m new to coding for WordPress Themes, and was wondering if you could explain your code a little more. It’s a bit confusing, and I can’t seem to get it working.

    Thank you

  5. I got the basic function working by adding a query_posts(‘showposts=3’); function. But I can’t create more than 2 loops.

  6. I tried the implementing the Loops on my site but it is not working at all. Any new suggestions?

  7. This is wonderful, thank you! I love the “post__not_in” trick, too. Using them both now at HealthyMindHeartBody.com. Thanks for the great post, wpr!

  8. how could one use 3 loops, the loops would be different categories that have the same article in them and also to make the categories with no duplicates?

Leave a Comment

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