To avoid post duplication, I started by creating a php array, and adding the IDs of the posts I get in the first loop to that array:
<h2>Loop n°1</h2>
<?php
$ids = array();
while (have_posts()) : the_post();
the_title();
?>
<br />
<?php $ids[]= $post->ID;
endwhile; ?>
Now, the second loop: I 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 n°2</h2>
<?php
query_posts("showposts=50");
while (have_posts()) : the_post();
if (!in_array($post->ID, $ids)) {
the_title();?>
<br />
<?php }
endwhile; ?>
That's done: 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.
8 Responses
Thanks for this short but extremely useful post. I’m implementing it now on a new project.
Thanks for the tip!! I’ve just have one question, I am a novice wp developer but is not better use the funcition “post__not_in…” ? Whats the difference?
Alternatively you second and any loop following could look like this:
Loop n°2
’20′, ‘post__not_in’ => $ids ) );
while ( have_posts() ) : the_post();
?>
ID;
endwhile; ?>
I’m new to coding for WordPress Themes, and was wondering if you could explain your code a little more. It’s a bit confusing, and I can’t seem to get it working.
Thank you
Will
I got the basic function working by adding a query_posts(‘showposts=3′); function. But I can’t create more than 2 loops.
I tried the implementing the Loops on my site but it is not working at all. Any new suggestions?
This is wonderful, thank you! I love the “post__not_in” trick, too. Using them both now at HealthyMindHeartBody.com. Thanks for the great post, wpr!
how could one use 3 loops, the loops would be different categories that have the same article in them and also to make the categories with no duplicates?
Trackbacks: