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? :)
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