1

how to avoid duplicate posts on front page? i have 1 category 'news' for all posts and some categories like 'vegetables' and 'fruits'. Each post is in 'news' and particular category.

At the top of page i have recent 3 'news' posts and in other places i want to press fe.3 recent posts for 'fruits' category, but to not duplicate 3 recent 'news' posts. i've tried with sth like that:

query_posts( 'posts_per_page=3&category_name=fuits' ) && query_posts('posts_per_page=3&category_name=news&offset=3' );

Can anyone help me?

1

1 Answer 1

3

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.
}
1
  • Nice use of wp_list_pluck()! I've never seen that function before.
    – mrwweb
    May 1, 2012 at 1:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.