Sort WordPress posts by numerical custom fields

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:

Read More
$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

Related posts

Leave a Reply

5 comments

  1. 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);
    
  2. 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.