How to Avoid Duplicate Post Display with Multiple Loops in WordPress

The trick to avoiding duplicate post display is to store the post ID from the first loop, then check against that in the second loop. Here is how you do it. Your first loop’s code need to look like this (notice the magic line):

1
2
3
4
5
6
7
8
<?php $my_query = new WP_Query('category_name=featured&posts_per_page=1');
  while ($my_query->have_posts()) : $my_query->the_post();
  $do_not_duplicate = $post->ID; //This is the magic line
?>
    <!-- Do stuff... -->
<?php endwhile; ?>

Now that we have stored the post ID from the first loop under $do_not_duplicate variable, lets add a check for that in our second loop. Your second loop code should look something like this:

1
2
3
4
5
6
7
<?php if (have_posts()) : while (have_posts()) : the_post();
  if( $post->ID == $do_not_duplicate ) continue; //This is the Magic Line
 ?>
   <!-- Do stuff... -->
  <?php endwhile; endif; ?>

As long as you add those two lines in there, your posts will NOT replicate. To all new theme designers, we hope this helps.

Leave a Reply