When/why does ‘$query->get( ‘tax_query’ );’ return empty?

AFAIK $query->get for main query works only with public query vars, i.e. vars that can be triggered via url, but nothing prevents to directly access directly to tax_query property of query, but notice that it is an object, instance of WP_Tax_Query and the current queried taxonomy arguments are in the queries property of that object.

Accessing to that property you avoid to run another query with get_term_by inside your function. As a side effect, single_cat_title will print the correct title:

function itsme_better_editions( $query ) {

  if ( $query->is_category() && $query->is_main_query() ) {

    $query->set( 'post_type', array( 'post' ) );

    $tax_query_obj = clone $query->tax_query;

    $tax_query_obj->queries[] = array(
      'taxonomy' => 'category',
      'field' => 'slug',
      'terms' => 'intl',
      'operator' => 'IN'
    );

    $tax_query = array('relation' => 'OR');

    foreach ( $tax_query_obj->queries as $q ) {
      $tax_query[] = $q;
    }

    $query->set('tax_query', $tax_query);
  }

}

add_action( 'pre_get_posts', 'itsme_better_editions' );

Note that actually you are running the filter also on admin queries, if is not what you want add && ! is_admin() inside first if conditional in function.

PS: a tip: when using 'pre_get_posts' you can use add_action instead of add_filter and not return anything, because the query is passed as reference.

Leave a Comment