As seen on the great WP Engineer website: http://wpengineer.com/1719/filter-duplicate-posts-in-the-loop/?codekitCB=400689137.981452
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
<pre lang="php"><?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; ?></pre>
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
<pre lang="php"><?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; ?></pre>
A Better Option?
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.
<pre lang="php"><?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; ?></pre>
Revisions
- September 20, 2013 @ 00:24:32 [Current Revision] by PeterLugg
- September 20, 2013 @ 00:24:32 by PeterLugg
No comments yet.