pre_get_posts with tax_query causes empty result

You use tax_query incorrectly. Take a look at Codex Page

tax_query should be an array which can contain:

  • relation – it should be string (AND/OR)
  • taxonomy term – array with defined taxonomy, field, terms, and so on.

In your code your setting tax_query to:

$taxquery = array(
    'post_type' => 'post',
    'tax_query' => array(
        array(
            'taxonomy' => 'myposttypes',
            'field'    => 'slug',
            'terms'    => $term_slug
        ),
     ),
);

And it should be:

$taxquery = array(
    array(
        'taxonomy' => 'myposttypes',
        'field'    => 'slug',
        'terms'    => $term_slug
    ),
);

post_type is another param, so you can’t set it inside tax_query.

But… You still should be careful, if you change tax_query – it may have a value already. So if you want to be respectful of that, you should use something like this:

$tax_query = $query->get( 'tax_query' );
if ( ! is_array( $tax_query ) ) {
    $tax_query = array();
}
$taxquery[] = array(
    'taxonomy' => 'myposttypes',
    'field'    => 'slug',
    'terms'    => $term_slug
);
$query->set( 'tax_query', $taxquery );

This way you will add your tax query to already existing queries and not override them.

Leave a Comment