WP_Query – Order results by meta value

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x