WP_Query Woocommerce products that belong in distinct multiple categories only tax_query

后端 未结 4 576
猫巷女王i
猫巷女王i 2021-01-31 21:04

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 =         


        
4条回答
  •  生来不讨喜
    2021-01-31 21:19

    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; 
    

提交回复
热议问题