简体   繁体   中英

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?

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',
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM