please help me. I cant use meta_query to filter products with a price range
if ( ! empty( $data['price_range'] ) ) {
$price_range = explode( '|', esc_attr($data['price_range']) );
if ( is_array($price_range) && count($price_range) == 2 ) {
$args['meta_query'][] = array(
'key' => '_price',
'value' => array(reset($price_range), end($price_range)),
'compare' => 'BETWEEN',
'type' => 'NUMERIC'
);
}
}
$products = wc_get_products( $args );
and this for final "$args" value
[meta_query] => Array
(
[0] => Array
(
[key] => _price
[value] => Array
(
[0] => 6.28
[1] => 6.56
)
[compare] => BETWEEN
[type] => NUMERIC
)
)
other "$args" value is [post_status] => publish [post_type] => Array ( [0] => product [1] => product_variation )
thanks for your help before
CodePudding user response:
I believe to use meta_query with wc_get_products you have to follow the “adding custom parameter support” section at the bottom of this page wc_get_products
It is not otherwise supported. So you would otherwise need to use get_posts
CodePudding user response:
add_filter('woocommerce_product_data_store_cpt_get_products_query', 'handle_price_range_query_var', 10, 2);
function handle_price_range_query_var($query, $query_vars) {
if (!empty($query_vars['price_range'])) {
$price_range = esc_attr($query_vars['price_range']);
if (is_array($price_range) && count($price_range) == 2) {
$args['meta_query'][] = array(
'key' => '_price',
'value' => array(reset($price_range), end($price_range)),
'compare' => 'BETWEEN',
'type' => 'NUMERIC'
);
$query['orderby'] = 'meta_value_num'; // sort by price
$query['order'] = 'ASC'; // In ascending order
}
}
return $query;
}
Add the above code in your active theme fucntions.php and use the function below to get (custom filter) the products between the price range.
$args['price_range'] = array(6.8,6.56);
$products = wc_get_products($args);
Tested OK with WooCommerce 6.4