So I have custom taxonomy called “cars”. I would want that when user does search, it would also search through taxonomy. Meaning that in “cars” taxonomy if I have “Audi” term and user search with keyword “audi” it would then return posts that are tagged with term “audi”.
I tried this:
function mytheme_pre_get_posts( $query ) {
$query->set( 'tax_query', array(
array(
'taxonomy' => 'cars',
'field' => 'name',
'terms' => $_GET['s'],
)
));
add_action( 'pre_get_posts', 'mytheme_pre_get_posts', 1 );
But that breaks the search completely. Can this be done even or did I miss something?
You could try unsetting the original search query, otherwise you may be doubling up and the combination results in nothing? eg, try adding to your function:
$query->set('s','');
UPDATE
I am not sure on this one, but you could try the AND
operator -I think this adds to the existing query instead of replacing it…
function mytheme_pre_get_posts( $query ) {
if ( !is_admin() && $query->is_search() && $query->is_main_query() ) {
$term = get_term_by('name', get_query_var('s'), 'cars');
if ($term) {
$query->set( 'tax_query', array(
array(
'taxonomy' => 'cars',
'field' => 'slug',
'terms' => $term->slug,
'operator' => 'AND'
)
));
}
}
}
add_action( 'pre_get_posts', 'mytheme_pre_get_posts', 1 );
Note: changed use of field name
as mentioned by @PieterGoosen to slug
, and pre-fetched term slug to pass to tax query, and extra conditions as mentioned by @birgire.