I'm trying to avoid duplicates posts in one file - index.php where i do collection of the loops for categories. But no result. Please - help...
<div class="container-fluid newgray">
<div class="container asia travel-news proppad">
<?php get_template_part( 'inc/slider-news' );?>
</div>
</div>
<div class="container-fluid best">
<div class="container travel-news proppad">
<?php get_template_part( 'inc/best' );?>
</div>
</div>
<div class="container-fluid newback over">
<div class="container last travel-news proppad">
<?php get_template_part( 'inc/latest' );?>
</div>
</div>
Trying use this code:
<?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;
?>
<?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 it works only when all loops in one php file…
This is How I wold do, don't waste your time repeating same code, it will be a hell if you need change something.
function post_by_cat_ecluding($cats, $per_page, $exclude = array()) {
$html = '';
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'category__in' => $cats,
'posts_per_page' => $per_page,
'post__not_in' => $exclude,
'offset' => 0
);
$loop = new WP_Query($args);
foreach ($loop->posts as $p) {
$exclude[] = $p->ID;
$html .= '<article><h2>'.$p->post_title.'</h2></article>';
}
return array('html' => $html, 'exclude' => $exclude);
}
$first_block = post_by_cat_ecluding(array(1,2), 5);
echo $first_block['html'];
$second_block = post_by_cat_ecluding(array(4,5), 15, $first_block['exclude']);
echo $second_block['html'];