Marc
Marc

Reputation: 4851

WordPress wp_query order by meta_value incorrect order numerically

I am working on a simple web application that is running off of WordPress to store and display high scores for a game. The scores are displayed highest to lowest on a page. Everything seems to work great, until one of the scores goes above 999, in which case it is placed in the wrong order.

In my application scores are saved as a string within a meta_value. I am querying posts and ordering them based off of this value.

Here are the args that I am passing to wp_query:

$args2 = array(
    'post_type' => 'scoreboard',
    'orderby' => 'meta_value',
    'meta_key' => 'score',
    'order' => 'DESC',
    'posts_per_page' => '-1',
);

Scores are returned in a like way. Note that 1000 is placed after 123:

777, 700, 601, 600, 567, 400, 123, 1000, 1

Can someone offer an explanation as to why this may be happening?

Upvotes: 0

Views: 760

Answers (1)

David
David

Reputation: 5937

You are sorting by string representation of the field 1000 is lower than 12 in string terms. Same as when sorting words ABBOTT will be higher than AA.

try

$args2 = array(
    'post_type' => 'scoreboard',
    'orderby' => 'meta_value_num',
    'meta_key' => 'score',
    'order' => 'DESC',
    'posts_per_page' => '-1',
);

Upvotes: 3

Related Questions