Woocommerce 按属性筛选产品

Woocommerce Filter Product by Attribute

我一直在搜索许多博客和论坛,但似乎还没有答案。所以我试图找到一种方法如何按属性过滤产品。我正在使用 ajax 提取数据并附加 it.The 问题是根据什么属性进行循环的查询是什么。

例子。
产品 A 有 Color:Blue,Red,Green 并且有品牌:BrandA , BrandB
产品 B 有 Color:Pink,Red,black.

我只想在不使用任何插件的情况下在单个查询中获取所有具有颜色 [红色和绿色] 和品牌 [BrandA] 属性的产品。 这是我的 functions.php

中的代码
function advanced_search(){

     $html = "";
     $args = array( 'post_type' => 'product','product_cat' => 'yarn');
     $loop = new WP_Query( $args );
     while ( $loop->have_posts() ){
         $loop->the_post();
         ob_start();
         get_template_part( 'templates/part', 'search-result' ); 
         $html = ob_get_contents();
         ob_end_clean();
     }  
     wp_send_json(array(  "product_id" => $product_id , "html"  => $html ));
}
add_action('wp_ajax_get_advanced_search', 'advanced_search');
add_action('wp_ajax_nopriv_get_advanced_search', 'advanced_search'); 

我不知道应该将产品属性放在查询中的什么位置。我非常希望有人为 this.Thank 你找到答案。

您应该能够通过使用 tax_query combined with your WP_Query 来实现您的目标。附件是一个使用 'Brand' 属性和其中的 'EVGA' 术语的小示例(WooCommerce 将变成 'pa_brand' - 产品属性品牌)。

$query = new WP_Query( array(
    'tax_query' => array(
        'relation'=>'AND',
        array(
            'taxonomy' => 'pa_brand',
            'field' => 'slug',
            'terms' => 'evga'
        )
    )
) );

您可以在上述链接中找到更多文档,将一些税务查询串在一起以获得额外的过滤和功能。