I am building an AJAX post filter using a single form with three select fields that allow the user to sort by three separate taxonomies (category
, region
, and country
). Everything is working well for each select field when used alone, but when I choose options in two or three of the fields I want to make sure that the tax_query
array has an additional relation
parameter set to AND
so that post results meet all of the conditions set in each field. Here's where I am starting from:
$args = array(
'orderby' => 'date',
'order' => $_POST['date'],
);
// Regions
if ( isset( $_POST['region_filter'] ) ) {
$args['tax_query'] = array(
array(
'taxonomy' => 'region',
'field' => 'id',
'terms' => $_POST['region_filter']
)
);
}
// Countries
if ( isset( $_POST['country_filter'] ) ) {
$args['tax_query'] = array(
array(
'taxonomy' => 'country',
'field' => 'id',
'terms' => $_POST['country_filter']
)
);
}
// Categories
if ( isset( $_POST['category_filter'] ) ) {
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $_POST['category_filter']
)
);
}
if (
isset( $_POST['region_filter'] ) && isset( $_POST['country_filter'] ) ||
isset( $_POST['region_filter'] ) && isset( $_POST['category_filter'] ) ||
isset( $_POST['country_filter'] ) && isset( $_POST['category_filter'] ) ||
isset( $_POST['region_filter'] ) && isset( $_POST['country_filter'] ) && isset( $_POST['category_filter'] )
) {
// All conditions must be true to return posts
$args['tax_query'] = array( 'relation'=>'AND' );
}
$filter_query = new WP_Query( $args );
Where am I missing the mark here? And a side question, the method I'm using to build my query seems very repetitive, and I'm sure there has to be a better, more DRY method I can use to trim this down a good bit. Suggestions are more than welcome.