
Question:
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
<ol><li>product1 - $1001</li> <li>product2 - $1006</li> <li>product3 - $996</li> <li>product4 - $999</li> <li>product5 - $1003 </li> <li>product6 - $1001</li> <li>product7 - $1005</li> <li>product8 - $1010</li> <li>product9 - $998 </li> <li>product10 - $990</li> </ol>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
<ul><li>two product with price greater than $1000 & </li> <li>two product with price greater than $1000 </li> </ul>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
Answer1: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.