1

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

1
  • WordPress doesn't let you store numbers as numbers? Commented Jul 9, 2012 at 21:21

5 Answers 5

3

If you would like to do it manually (though the answers referencing WP_Query are better options), a reasonably nice treatment might use array_multisort:

$arr = array(
  '$116.99',
  '$12.95',
  '$149.00',
  '$15.99'
);

$keys = array();

foreach ($arr as $value) {
    $keys[] = floatval(substr($value, 1));
}

array_multisort($keys, SORT_ASC, $arr);
Sign up to request clarification or add additional context in comments.

Comments

1

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 = new WP_Query( array ( 'orderby' => 'meta_value_num', 'meta_key' => 'price' ) );

$query then contains rows of posts sorted numerically by price.

Comments

0

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.

Comments

0

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

Comments

0
function order($a, $b) {return intval($b) - intval($a);}
uasort($array, 'order');

I wonder that can help you ;)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.