I have two post types (type-A and type-B) and two taxonomies (tax-1 and tax-2), both assigned to each post type. This means that posts from type-A can contain terms from tax-1 and tax-2 and posts from type-B can also contain terms from tax-1 and tax-2.
I want my WP_Query to output all posts from type-A that contain certain terms of tax-1. But I don't want to output type-B posts that contain these tax-1 terms, which my WP_Query unfortunately does. The same should apply to tax-2, whereby only posts from type-B that contain terms from tax-2 should be output.
I have already tried to create two $args for this, but I did not manage to merge the two $args.
function my_function($args) {
global $post;
$args = array(
'post_type' => array('type-A','type-B'),
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'tax-1',
'field' => 'term_id',
'terms' => array(11, 12, 13),
),
array(
'taxonomy' => 'tax-2',
'field' => 'term_id',
'terms' => array(21, 22, 23),
),
),
);
return $args;
}
I have two post types (type-A and type-B) and two taxonomies (tax-1 and tax-2), both assigned to each post type. This means that posts from type-A can contain terms from tax-1 and tax-2 and posts from type-B can also contain terms from tax-1 and tax-2.
I want my WP_Query to output all posts from type-A that contain certain terms of tax-1. But I don't want to output type-B posts that contain these tax-1 terms, which my WP_Query unfortunately does. The same should apply to tax-2, whereby only posts from type-B that contain terms from tax-2 should be output.
I have already tried to create two $args for this, but I did not manage to merge the two $args.
function my_function($args) {
global $post;
$args = array(
'post_type' => array('type-A','type-B'),
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'tax-1',
'field' => 'term_id',
'terms' => array(11, 12, 13),
),
array(
'taxonomy' => 'tax-2',
'field' => 'term_id',
'terms' => array(21, 22, 23),
),
),
);
return $args;
}
Share
Improve this question
edited Nov 10, 2020 at 10:50
RaWa
asked Nov 10, 2020 at 9:04
RaWaRaWa
32 bronze badges
1 Answer
Reset to default 1You could use pre_get_posts to conditionally add the tax_query depending on post-type, here's a simple example.
<?php
function wpse_377928( $the_query ){
$post_type = $the_query->get('post_type');
if ( 'type_a' === $post_type ) {
$tax_query = [
[
'taxonomy' => 'tax-1',
'field' => 'term_id',
'terms' => array(11, 12, 13),
]
];
}
elseif ( 'type_b' === $post_type ) {
$tax_query = [
[
'taxonomy' => 'tax-2',
'field' => 'term_id',
'terms' => array(21, 22, 23),
]
];
}
if ( !empty( $tax_query ) ) {
$the_query->set( 'tax_query', $tax_query );
}
}
add_action('pre_get_posts', 'wpse_377928');