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

December 20, 2008 at 9:06 am

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.