Post Pic

How to: Use two (or more) loops without duplicate posts

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>
<?php
$ids = array();
while (have_posts()) : the_post();
the_title();
?>
<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>
<?php
query_posts("showposts=50");
while (have_posts()) : the_post();
if (!in_array($post->ID, $ids)) {
  the_title();?>
  <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.

Related Posts

Related Posts

No related posts.

8 Responses

Nov 16 2011 08:09

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

Feb 05 2012 19:03

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?

Feb 20 2012 13:07

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

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

ID;
endwhile; ?>

Jun 20 2012 13:16

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
Will

Jun 20 2012 13:39

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

Jul 20 2012 02:40

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

Jul 26 2012 05:45

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!

Aug 03 2012 17:21

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?

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required

WP Theme of the week

Sponsored Likebox