WP_Query Woocommerce products that belong in distinct multiple categories only tax_query
Wow, so after hours of banging my head, this is how I was able to solve this -
$args = array( 'posts_per_page' => -1, 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => 'category-slug1' ), array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => 'category-slug2' ) ), 'post_type' => 'product', 'orderby' => 'title',);$the_query = new WP_Query( $args );
This takes advantage of the tax_query
argument, including the relation => 'AND'
to make sure the product falls under BOTH categories.
Hope this helps someone in the future.
I was also not able to figure out how to pass an ID, rather than a slug (although I'm sure there's a way), but here's the function to retrieve the slug based on an ID:
$terms = get_term($YOURID, 'product_cat'); $theslug = $terms->slug;
To query by category_ID this is what worked for me.
// First obtain term id://...$all_categories = get_categories( $args );$cat_ids = array();foreach ($all_categories as $cat) { array_push($cat_ids, $cat->term_id);}//Now use ids from array:$args = array( 'posts_per_page' => -1, 'post_type' => 'product', 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'id', 'terms' => $cat_ids ) ));
From the WordPress codex on WP_Query
for Category Parameters:
equivalent of OR
$args = array( 'product_cat' => 'category-slug1,category-slug2' ) );
equivalent of AND
$args = array( 'product_cat' => 'category-slug1+category-slug2' );
e.g.
$query = new WP_Query( $args );