2015-02-06 83 views
0

我目前正在使用Woocommerce为WordPress网站构建我自己的自定义高级搜索功能。您应该可以使用过滤器来搜索:WooCommerce使用WP_Query在价格范围内搜索产品

  • 类别
  • 最大/最小价格

我目前的进展是附在下面。这使您能够在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。

回答

3

您可以在使用WP_Query(或get_posts,我发现在使用中侵入性较低)时组合多个meta_queries。

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' => '<=' 
      ) 
     ) 
    ) 
); 
2

一些解决方案,通过@Niels面包车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 
+0

啊,offcourse .. :) – 2015-02-06 14:47:03

2

如果你在woocom里面工作当你可以使用厕所钩梅尔切循环

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); 
} 
+0

谢谢你。这个对我有用。 – 2016-08-19 10:11:29

相关问题