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' ) );
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' ) );
Share
Improve this question
asked Dec 7, 2012 at 23:56
MichaelMichael
131 silver badge3 bronze badges
2 Answers
Reset to default 1You 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.
Good Reference from below link:
https://therichpost/wordpress-query-to-get-woocommerce-products-order-by-sales-pricing-and-rating/
'orderby' => 'meta_value_num',
'order' => 'asc',
'meta_key' => '_price'