WP_Query orderby meta_value_num not working

jonny-harte picture jonny-harte · Sep 29, 2016 · Viewed 10.3k times · Source

I'm trying to show list of services by price. I have setup the custom post type and custom fields etc. However, when I run the query on the page the most expensive service (£100) displays first instead of last... The query I've written is below:

$services = new WP_Query(array(
'post_type' => 'service',
'tax_query' => array(
    array(
        'taxonomy' => 'service_type',
        'field' => 'name',
        'terms' => $post->post_name,
    ),
),
'meta_key'  => 'price',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'meta_value_num',
'order' => 'ASC', ));

A link to the page is here dev.poshwashlondon.co.uk/valeting.

Thanks in advance!

Answer

muka.gergely picture muka.gergely · Sep 29, 2016

The link you provided clearly shows a string ordering (100, 15, 20, 25, etc.). Your problem seems to be that the meta value the query is using is not a number, but a string.

You can try this:

$services = new WP_Query(array(
'post_type' => 'service',
'tax_query' => array(
    array(
        'taxonomy' => 'service_type',
        'field' => 'name',
        'terms' => $post->post_name,
    ),
),
'meta_key'  => 'price',
'meta_type' => 'NUMERIC',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'meta_value_num',
'order' => 'ASC', ));

You can look at the possible "orderby"s here: https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters