在 woocommerce 中,我尝试检索具有全局属性 brand 的所有产品。根据我之前的理解和一些谷歌搜索,到目前为止我已经做到了这一点:
function handle_custom_query_var($query, $query_vars)
{
if (!empty($query_vars['with_brand'])) {
$query['meta_query'][] = array(
'key' => 'pa_brand',
'field' => 'term_id',
'compare' => 'EXISTS'
);
}
return $query;
}
add_filter('woocommerce_product_data_store_cpt_get_products_query', 'handle_custom_query_var', 10, 2);
$args = array(
'status' => 'publish',
'type' => 'simple',
'limit' => 50,
'paginate' => true,
'page' => $request['page'],
'with_brand' => true
);
$results = wc_get_products($args);
但我仍然得到没有品牌属性的简单产品。我做错了什么? // PS: 请忽略 wc_get_products 参数中不相关的参数
我也尝试过
'operator' => 'IN'
而不是
'compare' => 'EXISTS'
但是效果并不好。
您需要使用
tax_query
并且“比较”必须替换为“运算符”,例如:
add_filter('woocommerce_product_data_store_cpt_get_products_query', 'handle_pa_brand_product_attribute', 10, 2);
function handle_pa_brand_product_attribute($query, $query_vars)
{
if ( isset($query_vars['brand']) && $query_vars['brand'] === 'EXISTS' ) {
$query['tax_query'][] = array(
'taxonomy' => 'pa_brand',
'operator' => esc_attr($query_vars['brand']),
);
}
return $query;
}
那么您的 WC_Product_Query 将是:
$args = array(
'status' => 'publish',
'type' => 'simple',
'limit' => 50,
'paginate' => true,
'page' => $request['page'],
'brand' => 'EXISTS',
);
$results = wc_get_products($args);
已测试且有效。