questions

Tax query using AND relation for 2 category terms in WooCommerce

Rate this post

I want to get all my products, that are in the category A + B, I tried it with the tax_query, but until now I don’t have the expected results.

$args = array(
      'posts_per_page' => -1,
      'post_type' => 'product',
      'tax_query' => array(
         'relation' => 'AND',
          array(
            'taxonomy' => 'product_cat',
            'field'    => 'term_id',
            'terms'    => $_GET["terms"],
          )
        ),
  );

With that query I get the products that are in A or B…

 

✔️Solution:

Assuming that url parameters are passed a bit like ?terms[0]=15&terms[1]=22 (where 15 and 22 are the terms Ids), so $_GET["terms"] gives an array of terms Ids, then you will use the following:

$tax_query = array(); // Initializing

if( isset($_GET['terms']) && is_array($_GET['terms']) ) {
    $terms_ids = wc_clean($_GET['terms']); 

    $tax_query = count($terms_ids) > 1 ? array('relation' => 'AND') : array();

    // Loop through terms Ids
    foreach( $terms_ids as $term_id ) {
        $tax_query[] = array(
            'taxonomy' => 'product_cat',
            'field'    => 'term_id',
            'terms'    => $term_id,
        );
    }
}

$args = array(
    'posts_per_page' => -1,
    'post_type'      => 'product',
    'post_status'    => 'publish',
    'tax_query'      => $tax_query
);

Tested and works.

Leave a Reply

Your email address will not be published.

Back to top button