0

I have two custom post types. businesses profiles sharing a single taxonomy locations.

When I use WP Query for retrieval of common posts it returns common posts. Here is the query I am using.

$queryargs = array(
    'post_type' => 'profile',
    'tax_query' => array(
        array(
            'taxonomy' => 'ait-locations',
            'field'    => 'term_id',
            'terms'    =>  array( 1071 ),
        ),
    ),
);

this query returns two posts. all good till here.

BUT when I use the wordpress search to do the same thing it results in no posts found.

Here is the URL I am using in the wordpress post

?s=&post_type=profile&ait-locations=1071

IF if on the search page I try global $wp_query; and then echo the query that is currently being executed on the search page it returns

array(3) {
  ["s"]=>
  string(0) ""
  ["post_type"]=>
  string(7) "profile"
  ["ait-locations"]=>
  string(4) "1071"
}
0

By default, WordPress searches by keyword. To use a custom query variable for search, you would have to register the custom query variable using query_vars

function wpse250276_register_query_vars( $vars ) {
    $vars[] = 'ait-locations';
    return $vars;
}
add_filter( 'query_vars', 'wpse250276_register_query_vars' );

Then you need to use pre_get_posts to alter search query and include your custom taxonomy filter using get_query_var

function wpse250276_pre_get_posts($query) {
    if ($query->is_search) {

        $tax_query = array();
        // add taxonomy query elements
        if( !empty( get_query_var( 'ait-locations' ) ) ){
            $tax_query[] = array(
                'taxonomy'  => 'ait-locations',
                'field'     => 'term_id',
                'terms'     => array( get_query_var( 'city' ) ),
            );

            $query->set( 'tax_query', $tax_query );
        }
    }
    return $query;
}
add_filter( 'pre_get_posts','wpse250276_pre_get_posts' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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