php – Limit a search box by CPT + taxonomies, in only one page

Question

I have a specific page, in which I want the search box to show only a CPT as result. But I also want to search, as input terms, for post title, and two custom taxonomies assigned to this CPT. I tried some reduced versions of code that worked, but never to the full extent.

Page is ‘Profissionais’, CPT ‘profissional’ and taxonomies ‘regiao’ and ‘cidade’.

This one works perfect, but on the whole site:

add_filter('pre_get_posts', 'filter_search_cpt_prof');
function filter_search_cpt_prof($query)
{
    if( $query->is_search ) $query->set('post_type', 'profissional');

    return $query;
}

But when I try something like this, it doesn’t work at all:

add_filter('pre_get_posts', 'filter_search_cpt_prof');
function filter_search_cpt_prof($query)
{
    if( $query->is_search() && $query->is_main_query() && is_page('profissionais') ) {
        $query->set('post_type', 'profissional');
    }
    return $query;
}

And of course, not this as well:

add_filter('pre_get_posts', 'filter_search_cpt_prof');
function filter_search_cpt_prof($query)
{
    if ($query->is_search) {
        $query->set('post_type', array('profissional'));
        $tax_query = array(
            'relation' => 'OR',
            array(
                'taxonomy' => 'regiao',
                'field' => 'name',
                'terms' => $query->query_vars['s'],
            ),
            array(
                'taxonomy' => 'cidade',
                'field' => 'name',
                'terms' => $query->query_vars['s'],
            ),
        );
        $query->set('tax_query', $tax_query);
    }

    return $query;
}

I have spent uncountable hours in this… Anyone can help?

0
Filipe 2 months 2023-03-24T23:20:08-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse