Tell me more ×
WordPress Answers is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm addressing a well known issue in Wordpress, in which I want to display "featured" posts, and under it the rest of the posts.
I have a $query1 which holds 2 featured posts, and my query_posts which holds all of the posts on the site (including those two from $query1).
I now wish to remove from query_posts those two posts so I can display it using regular Wordpress loop in the form of:

while (have_posts ()) : the_post();
the_title();
the_content();
endwhile;


I have the solution for removing these duplicate posts inside the above loop, but because of the paging, I want to have the query without duplicates before that, so the query_posts array will be paged without those two featured posts.

share|improve this question

1 Answer

Based on several different answers, with a SPECIAL thanks to EAMann's similar answer - here's the method I followed.

  1. Using new WP_Query instead of query_posts for this page.
  2. Defining the query variable ($main_query) as global.
  3. Querying a temp array ($temp_featured) with my featured posts.
  4. Creating an array with only the IDs of the `$temp_featured'. Note EAMann's use of the wp_list_pluck function.
  5. Executing the main query of the page ($main_query) with the argument to exclude the IDs retrieved in #4.

This is how it came out all in all:

global $main_query; 

$temp_featured = get_posts( 
    array(
        'post_type' => 'custom_post',
        'custom_post-category' => 'featured-cat', 
        'posts_per_page' => 2)
        );
$featured_ids = wp_list_pluck( $temp_featured, 'ID' );

$query_args =  array(
                'post_type' => 'custom_post',  
                'posts_per_page' => $per_page, 
                'paged' => $current_page, 
                'post__not_in'   => $featured_ids
                );
$main_query = new WP_query ($query_args);

//displaying the two featured posts with their own query
$featured = new WP_query( array(
                            'post_type' => 'custom_post',
                            'custom_post-category' => 'featured-cat',
                            'posts_per_page' => 2)
                            );
while ($featured->have_posts ()) : $featured->the_post();
    the_title();
    the_excerpt();
endwhile;

//displaying the full query of the page
if ($main_query->have_posts ()) : 
    while ($main_query->have_posts ()) : $main_query->the_post();
        the_title();
        the_excerpt();
    endwhile;
endif;


I hope this helps anyone - please edit/comment or contact me if you have some further thoughts or inquiries.

share|improve this answer

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.