In woocommerce I's trying to retrieve all products that have global attribute brand. from my prior understandings and also some googling I have done this so far:
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);
but still I'm getting simple products with no brand attribute. what I'm doing wrong? // PS: kindly ignore unrelated paramethers inside wc_get_products arguments
I also tried
'operator' => 'IN'
instead of
'compare' => 'EXISTS'
But it did not work as well.
You need to use a
tax_queryand 'compare' has to be replaced with 'operator' like:Then your WC_Product_Query will be:
Tested and works.
Addition: Handling multiple product attributes.
You can handle multiple product attributes (here we use "Brand" and "Color"):
Then an example of WC_Product_Query using both: