• Posted: 2011-01-14
  • Author: Marko Petkovic
  • Tags:

Avoid Duplicate Posts in Multiple Loops

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10.  
  11.  
  12.  
  13.  
  14.  
  15.  
  16.  
  17.  
<h2>Loop n°1</h2>
<?php
$ids = array();
while (have_posts()) : the_post();
the_title();
?>
<?php $ids[]= $post->ID;
endwhile; ?>

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

Instructions:

Let’s start by creating a simple PHP array, and put all post IDs from the first loop in it.

Now, the second loop: we use the PHP function in_array() to check if a post ID is contained in the $ids array. If the ID isn’t contained in the array, we can display the post because it wasn’t displayed in the first loop.


Share this snippet

If you like this snippet, share it with friends!