views:

122

answers:

1

How Can I sort the custom field data numerically which is stored as string. I can't change it into database.

query_posts($query_string. '&orderby=meta_value&meta_key=price&order=DESC' );

This is what I am using but it is sorting it as string as this is stored as string as well.

Can anyone tell me how can I convert it into numerically without changing in database?

Thanks in advance.

Mazy

A: 

You can do it with a custom query string that castes the string meta data:

$querystr = "
    SELECT wposts.*
    FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
    WHERE wposts.ID = wpostmeta.post_id
    AND wpostmeta.meta_key = 'price' 
    AND wposts.post_type = 'post'
    ORDER BY ABS(wpostmeta.meta_value) DESC
";

If your meta value includes a dollar sign ($123.45), you can tweak the ORDER BY to remove it:

    ORDER BY ABS(SUBSTRING(wpostmeta.meta_value, 2)) DESC
Pat
It still don't work for me :( it is still coming as string and giving me result like this:21300 > 2750 > 25700 > 40000 > 30000 > 20000 > 25000 > 5000It should be: 40000 > 30000 > 25700 > 25000 > and so on....
mazy
Hmmmm, how about you give CAST() a try in the ORDER BY clause (http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html#function_cast). Something like `ORDER BY CAST(wpostmeta.meta_value AS DECIMAL) DESC`.
Pat