0

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.

1 Answer 1

1

Each of your code blocks will overwrite the previous, you need to add to the array rather than replace it:

$args['tax_query'][] = array(
    'taxonomy' => 'region',
    'field'    => 'id',
    'terms'    => $_POST['region_filter']
);

relation is AND by default, so you can just omit it, but if you wanted to explicitly set it:

$args['tax_query']['relation'] = 'AND';
0

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.