WooCommerce 无法使用 meta_query 来过滤具有价格范围的产品

问题描述 投票:0回答:2

请帮助我。我无法使用meta_query来过滤具有价格范围的产品

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 );

这就是最终的“$args”值

[meta_query] => Array
    (
        [0] => Array
            (
                [key] => _price
                [value] => Array
                    (
                        [0] => 6.28
                        [1] => 6.56
                    )

                [compare] => BETWEEN
                [type] => NUMERIC
            )

    )

其他“$args”值为 [post_status] => 发布 [post_type] => 数组 ( [0] => 产品 [1] => 产品变体 )

感谢您之前的帮助

wordpress woocommerce filter hook-woocommerce
2个回答
2
投票
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;
}

将上述代码添加到您的活动主题 fucntions.php 中,并使用下面的函数来获取(自定义过滤器)价格范围内的产品。

$args['price_range'] = array(6.8,6.56);
$products = wc_get_products($args);

使用 WooCommerce 6.4

测试正常

0
投票

我相信要将meta_query与wc_get_products一起使用,您必须遵循本页底部的“添加自定义参数支持”部分wc_get_products

不支持其他方式。所以你否则需要使用 get_posts

© www.soinside.com 2019 - 2024. All rights reserved.