I need to adjust the main loop for all archive pages in the following way.
I have registered a custom taxonomy “myposttypes”. Every single post is assigned to exactly one term of “myposttypes”.
If it is a category or tag archive page, only posts with “myposttypes->term1” should be included into the query result.
If it is a custom taxonomy archive page only posts with “myposttypes->term2” should be included into the query result.
I’ve already implemented the corresponsing pre_get_posts
hook but I’m not getting any results at all for all my archive pages. I have plenty of posts with corresponding taxonomies in my blog instance so there should be results.
Here is my approach:
function wpmw_adjust_archive_queries( $query ) {
if ( ! is_admin() && is_archive() && $query->is_main_query() ) {
if ( is_category() || is_tag() ) $term_slug = 'term1';
if ( is_tax( 'beitragsarten', 'news' ) ) $term_slug = 'term2';
$taxquery = array(
'tax_query' => array(
array(
'taxonomy' => 'myposttypes',
'field' => 'slug',
'terms' => $term_slug
),
),
);
$query->set( 'tax_query', $taxquery );
}
}
add_action( 'pre_get_posts', 'wpmw_adjust_archive_queries' );
UPDATE:
Here is my adjusted and simplified approach, that still does not work unfortunately. I get an empty result. I var_dump’ed $query and tax_query seems to be added correctly to query_vars.
function wpmw_adjust_archive_queries( $query ) {
if ( ! is_admin() && $query->is_archive() && $query->is_main_query() ) {
$tax_query = $query->get( 'tax_query' ) ? : array();
$tax_query[] = array(
'taxonomy' => 'myposttypes',
'field' => 'slug',
'terms' => array( 'term1' ),
'operator' => 'IN'
);
$query->set( 'tax_query', $tax_query );
}
}
add_action( 'pre_get_posts', 'wpmw_adjust_archive_queries' );
Here is the corresponding part of $query
[tax_query] => Array
(
[0] => Array
(
[taxonomy] => myposttypes
[field] => slug
[terms] => Array
(
[0] => term1
)
[operator] => IN
)
)