Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
    
the codex deals with that: codex.wordpress.org/The_Loop#Multiple_Loops –  Michael Apr 30 '12 at 18:56
add comment

1 Answer 1

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.
}
share|improve this answer
    
Nice use of wp_list_pluck()! I've never seen that function before. –  mrwweb May 1 '12 at 1:13
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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