WooCommerce使用WP_Query在价格范围之间搜索产品


WooCommerce search products between price range using WP_Query

我目前正在使用Wooccommerce为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_Query实现这一点。

该解决方案的灵感来自@Niels van Renselaar,但更干净:

$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

您可以在使用WP_Query(或get_posts,我发现它在使用中干扰较小)时组合多个meta_Query。

http://codex.wordpress.org/Class_Reference/WP_Meta_Query

http://codex.wordpress.org/Class_Reference/WP_Query

你可以通过做这样的来组合它们

$myposts = get_posts(
    array(
        'post_type' => array('product', 'product_variation'),
        'meta_query' => array(
            array(
                'key' => '_price',
                'value' => '200',
                'compare' => '>='
            ),
            array(
                'key' => '_price',
                'value' => '2000',
                'compare' => '<='
            )
        )
    )
);

如果您在wooccommerce循环中工作,何时可以使用WChook

add_action( 'woocommerce_product_query', 'example_product_query_price' );
function example_product_query_price ( $q ) {
    $meta_query = $q->get( 'meta_query' );
    $meta_query[] = array(
        'key'     => '_regular_price',
        'value'   => array(
            300000 ,
            900000
        ),
        'compare' => 'BETWEEN',
        'type'=> 'NUMERIC'
    );
    $q->set( 'meta_query', $meta_query );
}