I have a custom post type Wine
, which has an ACF Field that links to another custom post type Producer
as a post_object
relation. In my Producer, I have a custom taxonomy named Region
.
Now, what I’m trying to do is to query all the white wines where the producer’s region is x.
Here’s what I’ve tried:
$args = array(
'post_type' => 'wines',
'posts_per_page' => 12,
'tax_query' => array(
array(
'taxonomy' => 'type',
'field' => 'slug',
'terms' => 'white'
),
array(
'taxonomy' => 'region',
'field' => 'slug',
'terms' => 'alsace'
)
)
);
The problem I’m having is the tax_query
is executed on the wine
and not it’s producer
. I’ve looked at the documentation of WP_Query and can’t seem to find an example on how to achieve it.
Could anyone please guide me?
Thanks.
Update 1
I’ve retrieved the list of IDs of the producers to add it to the meta_query
:
$producers = new WP_Query(
array(
'post_type' => 'producers',
'posts_per_page' => -1
)
);
$producersIds = wp_list_pluck($producers, 'ID');
After that, I’ve updated the $args
by adding the meta query:
'meta_query' => array(
array(
'key' => 'producer',
'value' => $producerIds,
'compare' => 'IN'
)
)
1 Answer
Update 1
As @Florian pointed out, we do not need to use the wp_list_pluck function, we could simply add the 'fields' => 'ids'
to the WP_Query to retrieve the list of ids:
$producers = new WP_Query(
array(
'fields' => 'ids',
'post_type' => 'producers',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'region',
'field' => 'slug',
'terms' => 'alsace'
)
)
)
);
Then retrieve the wines by replacing $producerIds
by $producers->posts
.
Solution
First, I had to retrieve the producers from the region:
$producers = new WP_Query(
array(
'post_type' => 'producers',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'region',
'field' => 'slug',
'terms' => 'alsace'
)
)
)
);
Then I retrieve the list of ids with wp_list_pluck:
$producerIds = wp_list_pluck($producers->posts, 'ID');
And finally, I retrieve the wines with the ids of the producers:
$wines = new WP_Query(
array(
'post_type' => 'wines',
'posts_per_page' => 12,
'tax_query' => array(
array(
'taxonomy' => 'type',
'field' => 'slug',
'terms' => 'white'
)
),
'meta_query' => array(
array(
'key' => 'producer',
'value' => $producerIds,
'compare' => 'IN'
)
)
)
);