Not too long ago one in all our customers bumped into the difficulty of getting duplicate put up whereas growing a customized theme. What he was attempting to do was present the latest put up on the homepage, after which present an inventory of random posts in a separate loop on the identical web page. The difficulty was that the latest put up would someday be duplicated within the random put up loop. On this article, we'll present you methods to keep away from duplicate put up show when utilizing a number of loops in WordPress.
The trick to avoiding duplicate put up show is to retailer the put up ID from the primary loop, then test towards that within the second loop. Right here is the way you do it. Your first loop’s code must seem like this (discover the magic line):
<?php $my_query = new WP_Query('category_name=featured&posts_per_page=1'); whereas ($my_query->have_posts()) : $my_query->the_post(); $do_not_duplicate = $post->ID; //That is the magic line ?> <!-- Do stuff... --> <?php endwhile; ?>
Now that now we have saved the put up ID from the primary loop beneath $do_not_duplicate variable, lets add a test for that in our second loop. Your second loop code ought to look one thing like this:
<?php if (have_posts()) : whereas (have_posts()) : the_post(); if( $post->ID == $do_not_duplicate ) proceed; //That is the Magic Line ?> <!-- Do stuff... --> <?php endwhile; endif; ?>
So long as you add these two traces in there, your posts will NOT replicate. To all new theme designers, we hope this helps.