Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WP_Query orderby meta_value_num not working

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!

like image 957
jonny-harte Avatar asked Sep 29 '16 15:09

jonny-harte


2 Answers

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

like image 148
muka.gergely Avatar answered Oct 05 '22 01:10

muka.gergely


I know it's old question, byt maybe my answer will help somebody.

Problem here is that prices are strings as @muka-gergely mentioned, so the sorting will be alphabetical which is fine for strings (i.e. words), but can be unexpected for numbers (e.g. 1, 3, 34, 4, 56, 6, etc, rather than 1, 3, 4, 6, 34, 56 as you might naturally expect).

If you want to sort numbers from lowest to highest you have to add 'meta_type' to your query

$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',
'meta_type' => 'NUMERIC', //HERE
'order' => 'ASC', ));

Possible values for 'meta_type' are 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'

For more: https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters

like image 43
S1awek Avatar answered Oct 04 '22 23:10

S1awek