在WooCommerce中使用AND关系查询2个类别词的纳税查询

问题描述

我想获得我所有属于A + B类的产品,我使用tax_query进行了尝试,但是直到现在我还没有得到预期的结果。

$args = array(
      'posts_per_page' => -1,'post_type' => 'product','tax_query' => array(
         'relation' => 'AND',array(
            'taxonomy' => 'product_cat','field'    => 'term_id','terms'    => $_GET["terms"],)
        ),);

通过该查询,我得到A或B中的产品...

解决方法

已更新

假设传递的url参数有点像?terms[0]=15&terms[1]=22 (其中1522是ID),所以$_GET["terms"]给出了一组术语ID,那么您将使用以下代码:

$tax_query = array(); // Initializing

if( isset($_GET['terms']) && is_array($_GET['terms']) ) {
    $terms_ids = wc_clean($_GET['terms']); 

    $tax_query = count($terms_ids) > 1 ? array('relation' => 'AND') : array();

    // Loop through terms Ids
    foreach( $terms_ids as $term_id ) {
        $tax_query[] = array(
            'taxonomy' => 'product_cat','field'    => 'term_id','terms'    => $term_id,);
    }
}

$args = array(
    'posts_per_page' => -1,'post_type'      => 'product','post_status'    => 'publish','tax_query'      => $tax_query
);

经过测试可以正常工作。