How to Avoid Duplicate Post Display with Multiple Loops in WordPress
Recently one of our users ran into the issue of having duplicate post while developing a custom theme. What he was trying to do was show the most recent post on the homepage, and then show a list of random posts in a separate loop on the same page. The issue was that the most recent post would sometime be duplicated in the random post loop. In this article, we will show you how to avoid duplicate post display when using 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):
<?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:
<?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.