I want to filter search results by custom post type and custom taxonomy terms, the result is here:
add_action('pre_get_posts','search_filter');
function search_filter($query) {
if($query->query_vars['s'] != '' && is_search())
{
$query->set('post_type', array('partner','event','product'));
$tax_query = array(
'relation' => 'OR',
array(
'taxonomy' => 'city',
'field' => 'slug',
'terms' => array( 'belgrade' )
)
);
$query->set( 'tax_query', $tax_query );
}
}
Posts from specific CPT works, but filter by a category, not. Why? :)
I want to filter search results by custom post type and custom taxonomy terms, the result is here:
add_action('pre_get_posts','search_filter');
function search_filter($query) {
if($query->query_vars['s'] != '' && is_search())
{
$query->set('post_type', array('partner','event','product'));
$tax_query = array(
'relation' => 'OR',
array(
'taxonomy' => 'city',
'field' => 'slug',
'terms' => array( 'belgrade' )
)
);
$query->set( 'tax_query', $tax_query );
}
}
Posts from specific CPT works, but filter by a category, not. Why? :)
Share Improve this question asked Feb 22, 2022 at 10:20 Milosh N.Milosh N. 2152 silver badges8 bronze badges 2 |1 Answer
Reset to default 0I think the issue here is you're using the relation where you only have one inner tax array. So, it should be without one.
$tax_query = array(
array(
'taxonomy' => 'city',
'field' => 'slug',
'terms' => array( 'belgrade' )
)
);
Here's a detailed explanation from WP: Taxonomy Parameters
- relation (string) – The logical relationship between each inner taxonomy array when there is more than one. Possible values are ‘AND’, ‘OR’. Do not use with a single inner taxonomy array.
is_search
always refers to$wp_query->is_search()
, but what if$query
is not the main query? Then the if statement won't match because$query->is_search()
might be true, butis_search()
will be false! Otherwise the result of this appears to be that you want to search 3 post types, but only the posts that are in the city of belgrade – Tom J Nowell ♦ Commented Feb 22, 2022 at 10:48