How to add taxonomy filter on the query fly?

You have a syntax-ish error, or a spelling one. There is a space after “taxonomy” in your tax_query array. If that were the sum of it I’d have just posted a comment, but additionally that $query->tax_query->queries[] = $workspace_taxonomy_query; line is pointless. Nothing changes with or without it. Don’t try to hack the array like that. Just use $query->set( 'tax_query', $workspace_taxonomy_query); as below (using a taxonomy and term that exists in my test environment):

// Add custom posts to main query (archive and home)
add_action( 'pre_get_posts', 'add_post_types_to_query' );

function add_post_types_to_query( $query ) {
    if ( (is_home() || is_category() || is_search()) && $query->is_main_query() && !is_admin() )
    {
        // Query all posts on index and category pages
        $query->set( 'post_type', array( 'post', 'page', 'definition', 'video', 'data_vizualization', 'quizz', 'talk', 'question', 'study', 'bibliography' ) );

        $workspace_taxonomy_query =
                    array(
                      array(
                        'taxonomy' =>  'post_tag',
                        'field'     =>  'slug',
                        'terms'     =>  array('test-4'),
                        'operator'  =>  'IN'
                      )
                    );
        $query->tax_query->queries[] = $workspace_taxonomy_query;

    }
    return $query;
}

Leave a Comment