0

I'm using WooCommerce and I'm trying to filter my products by price. My problem is that the meta_key is only taking into account the regular price and not the sale price.

As a result if a product is on sale, the sale price is ignored by my filter and all of the products are ordered by the regular price.

Is there a way I can order my products by both the regular price and the sale price? Any help will be greatly appreciated!

$args = array(
'post_type'      => 'product',
'post_status'    => 'publish',
'posts_per_page' => $posts_per_page,
'taxonomy'       => 'product_cat',
's'              => $search_term,
'orderby'        => 'meta_value_num',
'order'          => 'DESC',
'meta_key'       => '_price',
);
4
  • Are you sure you want to display products from the most expensive to the cheapest one? If yes your products with sale price will be on the bottom. Regular and sale price are stored in two places in _regular_price and _sales_price meta_key and in the same _price meta_key for sorting purpose (depending which is smaller I think). Try to investigate your database query to find problem. – kierzniak Dec 1 '17 at 8:48
  • Yes, I'd like to arrange them from lowest to highest and vice versa. Is possible to create a function that checks for the lower price between _regular_price and _sale_price (if _sale_price isn't empty) and then store this data in a new meta_key in my database? – ed_mdk Dec 1 '17 at 9:13
  • Take a look at my answer. I don't think you need such a function. WooCommerce is taking care of handling price and updating _price meta_key. – kierzniak Dec 1 '17 at 9:28
  • Thanks, I'll try your solution as soon as I'm back on my PC. – ed_mdk Dec 1 '17 at 11:17
1

When your are updating your product regular price is saved to _regular_price and sale price is saved to _sale_price meta_key. Also WooCommerce will figure out which is the current price sale or regular and will save it to _price meta_key. There is no need to sort products by two _regular_price and _sale_price meta_keys. Your current prices should be stored in _price meta_key and this key should be used to sort products by price.

Try to investigate your SQL $query->request and database records to figure this out.

Keep in mind that if your sale price is scheduled you have to make sure that WooCommerce cron jobs are working correctly to update _price meta_key.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.