How to Avoid Duplicate Posts in Multiple Loops.
Advertisements
In the recent days almost every wordpress blog is using ‘Magazine’ type themes. But one problem associated with Magazine themes is that they use more than one loop on their blog home page for a solution to avoiding duplicate posts on the second loop.
Well this lttle php hack can solve this problem for you.
1. Let’s start by creating a simple PHP array, and put all post IDs from the first loop in it.
<h2>Loop n°1</h2>
<?php
$ids = array();
while (have_posts()) : the_post();
the_title();
?>
<br /><?php $ids[]= $post->ID;
endwhile; ?>
2. 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.
<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; ?>
How it works: At the time the first loop will be executed, all IDs of posts contained within it are put into an array variable. Now when the second loop is executed, we check that the current post ID hasn’t already been displayed in the first loop by referring to the array.
That’s all.
Source: http://www.wprecipes.com/how-to-use-two-or-more-loops-without-duplicate-posts

