Order Posts by Meta Value Numbers in Wordpress

The following changes work on Wordpress version 2.8.*, prior version will need a slightly different change.

A brief background first. I needed to have a page in which my posts were ordered by the meta_values to a particular meta_key. By default meta_value is LONGTEXT data in mysql, therefore we are unable to order posts by meta_value NUMBERS. To force mysql to return the meta_value entry as a NUMBER, we must pass a query like this: ‘meta_value+0′.

I set my custom page up to run a query_posts.

1
query_posts('meta_key=views&orderby=meta_value_number&order=DESC');

Then use The Loop as normal.

Inside query.php I did the following:
Goto line ~2035, add below

1
$allowed_keys[] = 'meta_value_number';

Goto line ~2057, after case break, add below

1
2
3
'meta_value_number':
$orderby = "$wpdb->postmeta.meta_value+0";
break;

Thats it! You can now pull posts ordered by meta_value NUMBERS!!

Remember that this method only works in 2.8.*, if you have an earlier version and would like to figure it out, or have a solution, please feel free to comment.

one reader comment

  1. Jefferson says:

    Hey man! Great, I have been trying to figure this out for some time. Thanks for this.

add your comment