I'm looking to use get_posts to return all posts within a specific term, plus some specific posts that may exist in another term. Ideally, I want to do this within one query. The issue is tax_query overrides any posts that aren't in that term. This is the code:
$args = array(
'numberposts' => -1,
'post_type' => 'books',
'post_status' => 'publish',
'include' => array(3181, 3180), //these are specific books that can be in any term
'tax_query' => array(
array(
'taxonomy' => 'genre',
'field' => 'id',
'terms' => array(152) //plus I need to get all books within this term
);
);
);
$my_posts = get_posts( $args );
var_dump($my_posts);
This only returns the posts within the fiction genre. This does not return the books with ID's 3181 and 3180.
Your help is much appreciated.
My Answer:
You can achieve this by using a combination of tax_query and post__in parameters in your query. Here's an updated version of your code:
php
$args = array(
'numberposts' => -1,
'post_type' => 'books',
'post_status' => 'publish',
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'genre',
'field' => 'id',
'terms' => array(152)
)
),
'post__in' => array(3181, 3180)
);
$my_posts = get_posts( $args );
var_dump($my_posts);
In this code, we are using the 'relation' parameter in the tax_query to specify that we want to include posts that match either of the conditions (posts in the genre with ID 152 or posts with IDs 3181 and 3180). We are also using the post__in parameter to include specific posts by their IDs.
This should return all posts within the genre with ID 152, as well as the specific posts with IDs 3181 and 3180.
Rate this post
4 of 5 based on 4845 votesComments