6

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!

1
  • The entries found on the page you linked seems to be ordered as strings, not numbers. If you cannot cast them to be numbers before querying, then the query must take this into account. Commented Sep 29, 2016 at 16:00

2 Answers 2

9

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

5

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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