I added a code that allows me to sort WordPress posts by custom fields. I’m trying to sort the posts by prices, but it’s sorting by the first number and not the value:
$116.99
$12.95
$149.00
$15.99
Instead of:
$12.95
$15.99
$116.99
$149.00
How can I get it to sort properly?
Here’s the code: http://pastebin.com/Pe5yfvrE
I took it from this discussion, but it was left unresolved there..
http://wordpress.org/support/topic/sort-posts-by-custom-field-in-backend
If you would like to do it manually (though the answers referencing
WP_Query
are better options), a reasonably nice treatment might usearray_multisort
:Use the WP_Query class and the orderby=meta_value_num parameter to sort numerically. Also, make sure you store the price in the custom field as a number without the “$” prepended.
$query
then contains rows of posts sorted numerically by price.I haven’t had a look at your code but you this has to do with the numbers being strings in your case. If you sort a string it is sorted like you describe. In order to sort it by it’s value you need to remove the
$
sign and cast it to a number.Did you see this technique? – adding zero to the meta value of the to force it to be treated as an integer. The post has been updated various times over the years too so it might help you;
http://wordpress.org/support/topic/order-by-meta_key-where-meta_value-is-number?replies=11
I wonder that can help you 😉