php – WordPress Conditional / Multiple Taxonomy Query

Question

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?

0
DANVC 3 weeks 2022-07-31T15:06:50-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse