Use two or more loops without duplicate wordpress posts
December 23, 2008 · Print This Article
How to use multiples loops without having the duplicate wordpress posts?
There’s probably many other ways to achieve the same effect.
But here’s a pretty nice way to avoid duplicate posts in two or more loops.
To avoid wordpress post duplication, we started by creating a php array.
And adding the IDs of the posts we get in the first loop to that array:
<h2>Loop NO1</h2>
<?php
$ids = array();
while (have_posts()) : the_post();
the_title();
?>
<br />
<?php $ids[]= $post->ID;
endwhile; ?>
Now, the second loop: we have used the php function in_array() to check out if a post ID is contained in the $ids array. If the IDs isn’t contained in the array, we can display the post as it wasn’t displayed on the first loop.
<h2>Loop NO2</h2>
<?php
query_posts("showposts=10");
while (have_posts()) : the_post();
if (!in_array($post->ID, $ids)) {
the_title();?>
<br />
<?php }
endwhile; ?>
Now no duplicated post.
Alternatively, it is possible to transform the $ids array to a comma separated string and use in along with the exclude parameter of the query_post() function.






















Comments
Got something to say?
You must be logged in to post a comment.