Search code examples
mysqlwordpressadvanced-custom-fields

order a WP query by specific custom field, not working


I want to order some posts by the number of downloads, DESC, and it seems the articles are random displayed:

$posts = get_posts(array(
‘post_type’ => ‘post’,
‘posts_per_page’ => 12,
‘meta_key’ => ‘post_views_count’,
‘orderby’ => ‘meta_value’,
‘order’ => ‘DESC’
));

But strange, the query from Mysql works just fine:

`SELECT * FROM wp_postmeta WHERE meta_key = ‘post_views_count’ ORDER BY meta_value DESC`

Any help is appreciated, thanks


Solution

  • Meta_Value field stores values as a string. That's why it returns orderby data in alphabetical order. f.e. 9,8,7,70,6,5,55,4,3,2,1 To get numerical orderby you should use meta_value_num.

    $posts = get_posts(array(
    'post_type' => 'post',
    'posts_per_page' => 12,
    'meta_key' => 'post_views_count',
    'orderby' => 'meta_value_num',
    'order' => 'DESC'
    ));
    

    And also, in your question text, commas are wrong. It should be ', not ‘