Exclude woocommerce products with no price set- wp

2019-07-23 06:11发布

I am trying to display the woocommerce products with almost similar regular price. For eg: Regular price of the current product is $1000

and some other products with prices are

  1. product1 - $1001
  2. product2 - $1006
  3. product3 - $996
  4. product4 - $999
  5. product5 - $1003
  6. product6 - $1001
  7. product7 - $1005
  8. product8 - $1010
  9. product9 - $998
  10. product10 - $990

Now if I was suppose to show 4 nearest products by price then they would be product 1,6,4,9

Because above seemed a bit difficult to me so I tried to get

  • two product with price greater than $1000 &
  • two product with price greater than $1000

Here are the arguments for wp query that I tried

$args =  array(
              'post_type'=>'product',
              'posts_per_page'=>2, 
              'order' => 'DESC',
              'orderby' => 'meta_value',
              'meta_key' => '_price',
              'meta_query' => array(
                                array(
                                'key' => '_price',
                                'value' => 1000,
                                'compare' => '<',
                                'type' => 'NUMERIC'
                              ),
                            )
             );

I guess it should give me 2 nearest products with prices less 1000

But issue is it also gives me products for which the price is not set ..So I want to exclude the products with no price set..

Thanks in advance

1条回答
贪生不怕死
2楼-- · 2019-07-23 07:00

You can use multiple meta queries, so you could add one to check if the price is higher then 0:

$args =  array(
              'post_type'=>'product',
              'posts_per_page'=>2, 
              'order' => 'DESC',
              'orderby' => 'meta_value',
              'meta_key' => '_price',
              'meta_query' => array(
                                array(
                                'key' => '_price',
                                'value' => 1000,
                                'compare' => '<',
                                'type' => 'NUMERIC'
                              ),
                                array(
                                'key' => '_price',
                                'value' => 0,
                                'compare' => '>',
                                'type' => 'NUMERIC'
                              )
                            )
             );

You do not need to set the relation parameter, as it is set to "AND" by default.

查看更多
登录 后发表回答