Search code examples
phpwordpressfilter

WordPress query_posts with multiple tax_query


The below query only works if $_POST['product_cat'] and $_POST['sub_category'] return something. How do I make this work if either one of these are empty?

In the end I will have 6 different optional taxonomies so I can't really have a separate query for every combination.

query_posts(array(
  'post_type' => 'product',
  'post_status' => 'publish',
  'tax_query' => array(
    'relation' => 'AND',
     array(
       'taxonomy' => 'product_cat',
       'terms' => $_POST['product_cat'],
     ),
     array(
       'taxonomy' => 'sub_category',
       // 'field' => 'slug',
       'terms' => $_POST['sub_category'],
     ),
     ...
   )
 ));

Solution

  • Easiest option is to construct the tax_query array based on the POST data and supply it to the WP_Query.

    Example:

    $tax_query = ['relation' => 'AND'];
    
    // List the parameters you are getting from POST data
    $post_filters = ['product_cat', 'sub_category', 'other_taxonomies'];
    
    // Loop through the post parameters and add them to the tax_query
    foreach ( $post_filters as $post_filter ) {
        if ( ! empty( $_POST[$post_filter] ) ) {
            $tax_query[] = [
                'taxonomy' => $post_filter,
                'terms' => $_POST[$post_filter]
            ];
        }
    }
    
    // And finally you can pass the $tax_query to the query
    query_posts(array(
        'post_type' => 'product',
        'post_status' => 'publish',
        'tax_query' => $tax_query
    ));