Mar
13

Avoid Duplicate Posts in Multiple Loops

sm3

The problem. Due to the recent popularity of “magazine” themes, there’s a high demand from WordPress users who use more than one loop on their blog home page for a solution to avoiding duplicate posts on the second loop.

The solution. Here’s a simple solution to that problem, using the power of PHP arrays.

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; ?>

Code explanation. When the first loop is being executed, all IDs of posts contained within it are put into an array variable. When the second loop executes, we check that the current post ID hasn’t already been displayed in the first loop by referring to the array.





Related posts


Want automatic updates? Subscribe to our RSS feed or
Get Email Updates sent directly to your inbox!
  • http://sepehr.mp Sepehr Lajevardi

    Not an efficient solution, you’ll loose all the second loop’s posts (say you want to show only 3 posts) if you have a first one with same three posts.
    Use `post__not_in` argument of `query_posts()` & that shall make it.
    cheers ;)

  • http://www.goboxy.com Go Boxy

    thank you, i guess you solution is so much better, i will update the post soon, thank you

  • http://sepehr.mp Sepehr Lajevardi

    You’re welcome ;)

  • pikavip

    I be enduring be familiar with a few of the articles on your website in the present circumstances, and I really like your line of blogging. I added it to my favorites trap stage list

  • tips

    I always like this is type of article. Thank you.