WP_Query Woocommerce产品属于不同的多个类别,只有tax_query

RCN*_*eil 14 wordpress categories woocommerce

我正在使用WP_QueryWoocommerce产品试图查询特定类别的产品.这是对我有用的语法 -

$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();
Run Code Online (Sandbox Code Playgroud)

这将返回的数据,但我想传递一个ID,而不是一个类别蛞蝓,过滤和我想找到存在于多个类别的产品.

这个论点product_cat不是原生的WP_Query(至少我能找到),所以我认为这是Woocommerce的习惯.通过他们的文档,我找不到任何允许我按类别ID过滤的内容,也没有使用AND条件进行过滤.

使用cat,数组tax_query,并category__and没有产生任何结果.基本上,我想查询类别ID 102和115中存在的所有产品.如果我必须使用slug,我确信有一种方法可以根据我的ID获取该信息,但我会喜欢避免2个查询按多个类别进行过滤.

有谁知道如何做到这一点?

更新:我已经了解到在product_cat参数中用逗号分隔类别slugs 会产生"OR"效果,因此它会组合两者的不同产品,但这不是我想要的.所以,例如:

 'product_cat' => 'category-slug1, category-slug2'
Run Code Online (Sandbox Code Playgroud)

将返回两个类别的产品,但我仍在寻找一种方法来查找仅属于两个或多个类别的不同产品.

RCN*_*eil 28

哇,经过几个小时的敲打,这就是我能够解决这个问题的方法 -

$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 );
Run Code Online (Sandbox Code Playgroud)

这利用了这个tax_query论点,包括relation => 'AND'确保产品属于两种类别.

希望这可以帮助将来的某个人.

我也无法弄清楚如何传递ID而不是slug(尽管我确定有一种方法),但这里是根据ID检索slug的功能:

$terms = get_term($YOURID, 'product_cat'); 
$theslug = $terms->slug; 
Run Code Online (Sandbox Code Playgroud)


小智 11

要按category_ID查询,这对我有用.

// 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
        )
    )
);
Run Code Online (Sandbox Code Playgroud)


小智 6

WP_Query类别参数的WordPress codex开始:

相当于OR

$args = array( 'product_cat' => 'category-slug1,category-slug2' ) );
Run Code Online (Sandbox Code Playgroud)

相当于AND

$args = array( 'product_cat' => 'category-slug1+category-slug2' );
Run Code Online (Sandbox Code Playgroud)

例如

$query = new WP_Query( $args );
Run Code Online (Sandbox Code Playgroud)