Get post ID's from one query and exclude from another

admin2025-04-17  1

I have 2 instances of the WP_Query class, one showing 4 "Featured" posts and another showing "basic" posts.

What I want to do is exclude those 4 latest "Featured" posts from the basic query. I assume it's just a case of adding a post__not_in variable but how can I get the ID's from the first query and exclude them from the second?

I have 2 instances of the WP_Query class, one showing 4 "Featured" posts and another showing "basic" posts.

What I want to do is exclude those 4 latest "Featured" posts from the basic query. I assume it's just a case of adding a post__not_in variable but how can I get the ID's from the first query and exclude them from the second?

Share Improve this question edited Jan 6, 2020 at 15:54 Viktor Borítás 3042 silver badges11 bronze badges asked Jul 29, 2013 at 8:13 PoisontonomesPoisontonomes 6064 gold badges17 silver badges28 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 3

While running the loop of the first query, just collect the IDs into an array. Example:

// define your first query's arguments
$args1 = array(
    ... your first query args
);
$query1 = new WP_Query($args1);
while ( $query1->have_posts() ): $query1->the_post();
    // this is your loop. Do whatever you want here
    // add this in the loop to collect the post IDs
    $exclude_posts[] = $post->ID;
endwhile;

// define your second query's arguments
$args2 = array(
    'post__not_in' => $exclude_posts,
    ... rest of your parameters
);
$query2 = new WP_Query($args2);
while ( $query2->have_posts() ): $query2->the_post();
    // this is your second loop. Do whatever you want here
endwhile;
wp_reset_postdata();
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744856930a270884.html

最新回复(0)