0

I am trying to create a custom WordPress taxonomy query with multiple but conditional statements. However I am having issues when more than one taxonomy query is added to the statement.

$tax_query = array('relation' => 'AND');

if (isset($_POST['category_id'])) {
  $tax_query[] =  array(
    'taxonomy' => 'category',
    'field'    => 'term_id',
    'terms'    => $_POST['category_id'],
  );
}

if (isset($_POST['insight_id'])) {
  $tax_query[] =  array(
    'taxonomy' => 'insight',
    'field' => 'term_id',
    'terms' => $_POST['insight_id'],
  );
}

if (isset($_POST['industry_id'])) {
  $tax_query[] =  array(
    'taxonomy' => 'industry',
    'field' => 'term_id',
    'terms' => $_POST['industry_id'],
  );
}

$query = new WP_Query(
  array(
    'posts_per_page' => -1,
    'tax_query' => $tax_query,
  )
);

My code is above.

If only Category ID exists, then the query should run as normal but if for example Category and an Insight ID exists, then it should find all posts with the taxonomy in Category and Insight. The same for Industry ID... I can't figure where I've gone wrong or why this doesn't work?

1
  • 1
    do you mean that if a category and an insight are specified then the post must have both, or do you mean it can have one of those? Because right now the way it's configured, a post will only be found it it meets all of those requirements at the same time. Also it's unclear where this code is or what the code that generates those arguments does. E.g. are these term IDs? term names? Does it work if you only add an insight without a category?
    – Tom J Nowell
    Jul 31 at 22:41

0

Your Answer

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

Browse other questions tagged or ask your own question.