78

I've checked around and haven't seen an answer which works as of yet. I have a WP_Query with the following arguments:

$args = array(
    'post_status' => 'publish',
    'post_type' => 'listing',
    'meta_key' => 'client_feedback_score',
    'orderby' => 'client_feedback_score',
    'order' => 'DESC'
);

$query = new WP_Query($args);

I want to order the results by the custom post field client_feedback_score, lowest to highest. But this doesn't seem to work... can anyone point me in the right direction?

EDIT (SOLVED):

Thanks to Milo's response, here's the working code for ordering by a numerical meta value:

$args = array(
    'post_status' => 'publish',
    'post_type' => 'listing',
    'meta_key' => 'client_feedback_score',
    'orderby' => 'meta_value_num',
    'order' => 'DESC'
);
0

2 Answers 2

99

orderby should be meta_value_num, or meta_value, not the name of the key. See WP_Query orderby parameters.

12
  • Worked a treat, cheers mate.
    – Adam Moss
    Oct 4, 2011 at 15:41
  • 14
    Small note, if the meta_key does not exist for the post yet, the post will be ignored.
    – adamj
    Dec 2, 2015 at 2:46
  • 1
    @RobBenz You should probably start a new question on this topic. Step 1 Assign whatever value you want to your meta key, let's call it my_meta_key, for each post to generate whatever order you want. Step 2 You set meta_key in your query to my_meta_key. This tells WordPress to query for posts that have that key. Step 3 Set orderby in your query to meta_value_num. This tells WordPress to not only query posts with my_meta_key, but to also order numerically by that key. That query argument is the only place you will ever see or use meta_value_num.
    – Milo
    Apr 25, 2017 at 18:21
  • 3
    @adamj is it any workaround this? I need sort all posts, regardless that meta_key exist for the post or not.
    – unbreak
    Feb 22, 2018 at 7:46
  • 1
    @unbreak the simple solution is to parse over all the posts and add the meta_key to them prior to running the order query
    – adamj
    Feb 23, 2018 at 9:21
9

if your meta value is not numeric for example if it is a date value; than you can add parameter meta_type => DATE. Possible values are; 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'.

Query with meta type will be like that:

$args = array(
'post_status' => 'publish',
'post_type' => 'listing',
'meta_key' => 'client_feedback_score',
'orderby' => 'meta_value_num',
'meta_type' => 'DATE',
'order' => 'DESC'
);

Not the answer you're looking for? Browse other questions tagged or ask your own question.