WooCommerce使用WP_QUERY在价格范围内搜索产品

时间:2015-02-06 作者:FooBar

我目前正在使用Woocommerce为WordPress网站构建自己的自定义高级搜索功能。您应该能够使用以下工具进行搜索:

我的当前进度附在下面。这使您能够在URL参数中指定类别段塞。返回的将是符合以下条件的帖子:

/**
 * Default arguments
 * @var array
 */

    $query = array(
        \'post_status\' => \'publish\',
        \'post_type\' => \'product\',
        \'posts_per_page\' => 10,
    );

/**
 * Category search
 */

    if(isset($_GET[\'categories\']) && $_GET[\'categories\']) {
        /**
         * Comma seperated --- explode
         * @var [type]
         */

            $categories = explode(\',\', $_GET[\'categories\']);

        /**
         * Add "or" parameter
         */

            $query[\'tax_query\'][\'relation\'] = \'OR\';

        /**
         * Add terms
         */

            foreach($categories as $category) {
                $query[\'tax_query\'][] = array(
                        \'taxonomy\' => \'product_cat\',
                        \'field\' => \'slug\',
                        \'terms\' => $category,
                    );
            }
    }
/**
 * Fetch
 */

    $wp_query = new WP_Query($query);
现在,虽然这在你搜索类别时效果很好,但当你需要搜索价格时,它似乎变得更加复杂。

在原始SQL中,可以使用以下方法:

SELECT DISTINCT ID, post_parent, post_type FROM $wpdb->posts
INNER JOIN $wpdb->postmeta ON ID = post_id
WHERE post_type IN ( \'product\', \'product_variation\' ) AND post_status = \'publish\' AND meta_key = \'_price\' AND meta_value BETWEEN 200 AND 1000
我不知道如何使用WP\\u Query实现这一点。

1 个回复
SO网友:FooBar

The solution:

$query = array(
    \'post_status\' => \'publish\',
    \'post_type\' => \'product\',
    \'posts_per_page\' => 10,
    \'meta_query\' => array(
    array(
        \'key\' => \'_price\',
        \'value\' => array(50, 100),
        \'compare\' => \'BETWEEN\',
        \'type\' => \'NUMERIC\'
        ),
    ),
);

$wpquery = WP_Query($query); // return 10 products within the price range 50 - 100
结束