Filter Duplicate Posts in the Loop

As the question arises quite often I'd like to show how I make sure that the content presented, which were output in a loop, not showed up again in a second loop.

WordPress identifies posts and pages via ID, which are created in the database and who also play in the output of the loop a crucial role. All assignments or links based on the ID. Therefore, I save in the first loop (Loop No.1 ) the IDs, which will be output, in an array. This variable was determined in advance as an array $do_not_duplicate = array();.

Loop no.1

<?php
$do_not_duplicate = array(); // set befor loop variable as array
 
// 1. Loop
query_posts('ca=1,2,3&showposts=5');
while ( have_posts() ) : the_post();
    $do_not_duplicate[] = $post->ID; // remember ID's in loop
    // display post ...
    the_title();
endwhile;
?>

After we output the above loop with 5 articles, we have in the array 5 IDs, which we can use now . You can view the array with the PHP-function var_dump().

In the next loop no. 2 there should be 15 articles displayed, except the articles with the ID's already appearing in loop no. 1. I check with this function in_array(),
if the current ID $post->ID is already existing in the array $do_not_duplicate. Only if the ID is not existing ( !in_array() ) in the array, then it will be displayed in loop no. 2.

Loop no.2

<?php
// 2. Loop
query_posts( 'cat=4,5,6&showposts=15' );
while (have_posts()) : the_post();
    if ( !in_array( $post->ID, $do_not_duplicate ) ) { // check IDs         
// display posts ...
        the_title();
    }
endwhile;
?>

But there is also an alternative, WordPress has a parameter in the query available - post__not_in, see Codex.
Also in this parameter, I use an array and in this query are the IDs not included. Depending on which way you go, are thus provides two different syntax, to avoid duplicate content.

<?php
// another loop without duplicates
query_posts( array(
    'cat' => 456,
    'post__not_in' => $do_not_duplicate
    )
);
while ( have_posts() ) : the_post();
    // display posts...
        the_title();
endwhile;
?>
3 Comments
  1. Banago says:

    Very nice way to work around it. I have been using another approach, but I like this one and I think I will start to use it. Thanks for sharing it!

  2. designerDru says:

    This is exactly what I've been looking for: 3 separate loops, the first displays the modt recent then sets a $do_not_duplicate to that ID.

    The 2nd loop grabs 6 posts from a specific category, & should not dupe the post from the first loop.

    The 3rd loop grabs 6 posts from a different specific category, & should also not dupe the post from the first loop.

    but no love from the code... If I pass it along would you be willing to take a look?

  3. Alt Design says:

    Hi, nice hacks... but what happens to the pagination (eg. wp_navi plugin)?

1 Ping
  1. Evita el contenido duplicado en tus Loops | Eliseos.net
Leave a Reply
WP Engineer Tags