1

I have a list of products on a page and am trying to order them by a custom field called "price". Unfortunately, $3,950,000 is coming before $349,000. I've used a couple of codes but neither one is working. Does anyone have any suggestions? Thanks.

Here's the first code I've tried.

$query = new WP_Query( array ( 'post_type' => 'product', 'orderby' => 'meta_value', 'meta_key' => 'price', 'order' => 'ASC' ) );

Here's the other code I've tried.

$query = new WP_Query( array ( 'post_type' => 'product', 'orderby' => 'meta_value_num+0', 'meta_key' => 'price', 'order' => 'ASC' ) );

2 Answers 2

1

You are storing your "price" (apparently) as human readable formatted currency. That makes it a string. And that means it is going to be sorted alphabetically, more or less, and not numerically as you need it to be. If you can store those values without the punctuation, and use meta_value_num-- your second query above (but I am not sure you need the "+0") -- I think you will have what you want.

3
  • That works! Thank you. Now I just need to find some code that will put the commas back in after the query.
    – Michael
    Commented Dec 8, 2012 at 0:35
  • PHP's number_format should get you a long way.
    – s_ha_dum
    Commented Dec 8, 2012 at 1:09
  • Make sure you use WordPress's i18n version of number format, so you get the internationalization benefits.
    – Otto
    Commented Dec 9, 2012 at 0:19
0

Good Reference from below link:

https://therichpost.com/wordpress-query-to-get-woocommerce-products-order-by-sales-pricing-and-rating/

'orderby' => 'meta_value_num',
'order' => 'asc',
'meta_key' => '_price'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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