WP_Query Woocommerce products that belong in distinct multiple categories only tax_query

◇◆丶佛笑我妖孽 提交于 2019-12-02 18:24:45

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
        )
    )
);
Daniel Twork

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 );

Inside a 'tax_query' array's array you can specify an 'operator' to be performed on the query. You can achieve what you want using the 'AND' operator.

$args = array(
'posts_per_page' => -1,
'tax_query' => array(
    'relation' => 'AND',
    array(
        'taxonomy' => 'product_cat',
        'field' => 'slug',
        'terms' => array( 'category-slug1', 'category-slug2' )
        'operator => 'AND',
    ),
),
'post_type' => 'product',
'orderby' => 'title',
);
$the_query = new WP_Query( $args );

All of the products selected by this query will match the provided 'terms'. See this link for more info: https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

In case the link ever breaks, here's the relevant info:

operator (string) - Operator to test. Possible values are 'IN', 'NOT IN', 'AND', 'EXISTS' and 'NOT EXISTS'. Default value is 'IN'.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!