First you want to make the query keys available so you can check them later:
add_action( 'init', 'custom_add_query_vars' );
function custom_add_query_vars() {
add_query_var( 'location' );
add_query_var( 'tag' );
}
Then you want to set a tax_query
by filtering the WP Query:
add_filter( 'pre_get_posts', 'custom_search_tax_query' );
function custom_search_tax_query() {
// check this is a search query with post type of 'listings'
if ( is_search() && get_query_var( 'post_type')
&& ( get_query_var( 'post_type' ) == 'listings' ) ) {
// check for location query var
if ( get_query_var( 'location' ) ) {
$location_query = array(
'taxonomy' => 'location',
'field' => 'slug',
'terms' => get_query_var( 'location' ),
);
}
// check for tag query var
if ( get_query_var( 'tag' ) ) {
$tag_query = array(
'taxonomy' => 'tag',
'field' => 'slug',
'terms' => get_query_var( 'tag' ),
);
}
// create the tax_query array
if ( isset( $location_query ) && isset( $tag_query ) ) {
$tax_query = array( 'relation' => 'AND', $location_query, $tag_query );
} elseif ( isset( $location_query ) ) {$tax_query = array( $location_query );}
elseif ( isset( $tag_query ) ) {$tax_query = array( $tag_query );}
// finally set the tax_query
if ( isset( $tax_query ) ) {$query->set( 'tax_query' => $tax_query );}
}
}
Then you should be fine to pass the inputs from your search form to the keys location
and tag
and get the responding posts you desire. 🙂
Notes:
- There is no need to return
$query
from the filter as it is passed by reference. - Strange as it may seem, the double-nested array of
$tax_query
is actually correct to allow for therelation
argument – whetherrelation
is set or not. - Be careful with
tag
, if you are actually using the standard tag taxonomy it will need to be changed topost_tag
(the taxonomy name for standard tags) in$tag_query
, but here I assume you have added an extra taxonomy actually calledtag
.