WooCommerce使用WP_Query搜索价格范围之间的产品 [英] WooCommerce search products between price range using WP_Query

查看:93
本文介绍了WooCommerce使用WP_Query搜索价格范围之间的产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Woocommerce为WordPress网站构建自己的自定义高级搜索功能.您应该可以使用过滤器进行搜索:

I am currently building my own custom advanced search functionality for a WordPress website with Woocommerce. You should be able to search using filter:

  • 类别
  • 最低/最高价格

我当前的进度附在下面.这使您可以在URL参数中指定类别标签.返回的帖子将匹配:

My current progress is attached below. This enables you to specify category slugs in the URL parameter. Returned will be posts that matches:

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

现在,虽然这在您搜索类别时效果很好,但是当您需要搜索价格时,它似乎变得更加复杂.

Now, while this works great when you're searching for categories it seems it gets way more complicated when you need to search through prices.

在原始SQL中,如下所示将起作用:

In raw SQL, something like below would work:

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_Query来实现它.

I have no idea how I could implement this using WP_Query.

推荐答案

该解决方案的灵感来自@Niels van Renselaar,但更为简洁:

The solution, inspired by @Niels van Renselaar, but more clean:

$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

这篇关于WooCommerce使用WP_Query搜索价格范围之间的产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆