0

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

2
  • 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, but is_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
  • I want to be safe to filter query only on the search page.
    – Milosh N.
    Commented Feb 22, 2022 at 10:51

1 Answer 1

0

I 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.
1
  • Thank you for answering. But this broke search, as a result, I don’t get a cpt results as before.
    – Milosh N.
    Commented Feb 22, 2022 at 10:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.