How to avoid duplicate posts on front page?

Don’t use an && like that. And don’t use query_posts() in the first place (It’s meant for modifying a query, not performing a separate query!) Instead, do your first selection, then pull out the IDs of the posts in that selection and pass them into the second query.

$fruit = get_posts( 
    array(
         'posts_per_page' => 3,
         'category_name'   => 'fruits'
    )
);

// Get an array with just the IDs of the posts in the $fruit array
$fruit_ids = wp_list_pluck( $fruit, 'ID' );

$news = get_posts( 
    array(
        'posts_per_page' => 3,
        'category_name'  => 'news',
        'post__not_in'   => $fruit_ids
    )
);

Your $fruit array now contains the three latest fruit posts and the $news array will now contain the 3 latest news posts (excluding the 3 posts in the $fruits array).

You can run through the loop like this:

foreach ( $news as $post ) {
    setup_postdata( $post );

    // Now use the_title(), the_content(), etc as usual.
}

Leave a Comment