Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WP_Query Woocommerce products that belong in distinct multiple categories only tax_query

I'm using WP_Query for Woocommerce products in attempt to query products in a particular category. This is the syntax that worked for me -

$args = array(
    'posts_per_page' => -1,
    'product_cat' => 'category-slug-here',
    'post_type' => 'product',
    'orderby' => 'title',
);
$the_query = new WP_Query( $args );
// The Loop
while ( $the_query->have_posts() ) {
    $the_query->the_post();
    echo '' . get_the_title() . '<br /><br />';
}
wp_reset_postdata();

This returns data, but I want to pass an ID, not a category slug, to filter and I want to find products that exist in multiple categories only.

The argument product_cat is not native to WP_Query (at least that I can find), so I'm assuming this is something custom to Woocommerce. Through their documentation, I haven't been able to find anything that will allow me to filter by category ID, nor use an AND condition for this filtering.

Using cat, the array of tax_query, and category__and have not yielded any results. Essentially, I would like to query all products that exist in both category ID 102, and 115. If I have to use slugs, I'm sure there is a way around getting that info based on the ID I have, but I'd like to avoid 2 queries to filter by multiple categories.

Does anyone know how to accomplish this?

UPDATE: I have learned that separating category slugs by commas in the product_cat argument will produce an "OR" effect, so it will combine distinct products from both, but this is not what I am looking for. So, for example:

 'product_cat' => 'category-slug1, category-slug2'

will return products from both categories in total, but I am still searching for a way to find distinct products that ONLY belong to both, or multiple, categories.

like image 328
RCNeil Avatar asked Dec 05 '13 22:12

RCNeil


1 Answers

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; 
like image 168
RCNeil Avatar answered Sep 28 '22 05:09

RCNeil