I am trying to query a custom post type based on what a user inputs into a form, I am having trouble querying multiple taxonomies in pre_get_posts filter, I can't seem to find a way to set the query more than one taxonomy
function custom_search( $query ) {
if ( is_archive('experts') && $query->is_main_query() && !is_admin() ) {
$keyword = get_query_var( 'keyword', FALSE );
$industry_select = strtolower(str_replace(' ', '-', get_query_var( 'industry_select', FALSE ) ));
$speciality_select = strtolower(str_replace(' ', '-', get_query_var( 'speciality', FALSE ) ));
// Keywords query
$keyword ? $keyword : $keyword = null;
$query->set('s', $keyword);
// Taxonomies query
$tax_query_array = array('relation' => 'OR');
$speciality_select ? array_push($tax_query_array, array('taxonomy' => 'experts_specialities', 'field' => 'slug', 'terms' => $speciality_select) ) : null ;
$query->set( 'tax_query', $tax_query_array);
$tax_query_array = array('relation' => 'OR');
$industry_select ? array_push($tax_query_array, array('taxonomy' => 'experts_industries', 'field' => 'slug', 'terms' => $industry_select) ) : null ;
$query->set( 'tax_query', $tax_query_array);
}}
add_action( 'pre_get_posts', 'custom_search' );
In the past I have written queries that look like the following that successfully look in two taxonomies (eventually I need to have 3 taxonomies though)
$featured_args = array(
'post_type' => 'experts',
'hide_empty' => false ,
'paged' => $paged,
'tax_query' => array(
array(
'taxonomy' => 'experts_industries',
'field' => 'slug',
'terms' => $broad_match_ind
),
array(
'taxonomy' => 'experts_specialities',
'field' => 'slug',
'terms' => $broad_match_spec
)
)
);
I'm trying to use pre_get_posts because I ultimately want the results of this query on an archive page and don't want to create a second query with a set of args ( as I am currently doing as evidenced by my second code example above )
Thanks in advance.
$tax_query_array = array('relation' => 'OR');
overrides the previous array.. Also,is_archive()
does not accept any parameters - useis_post_type_archive()
to check for a specific post type archive.