0

I have the following code below in my ~WP_Query`.

$args[ 'meta_key'] = 'price';
$args['orderby'] = 'meta_value meta_value_num';
$args['order'] = 'ASC';

The custom field in question has historic data that was created in a custom field and set as text. When I run my query I get the following results:

1,199.00, 1,299.99 169.99, 379.95.

which looks like a correct alpha sort. However, the higher numbers should appear last and the lower values first. I have tried to adjust the custom field to numeric, however I lose the custom field data.

Does anyone have a suggestion on how I should either rewrite my query or transfer my text custom field data to numeric data?

2

A meta_value field is always text; the fieldtype in the database structure is longtext, so unless you're explicitly typecasting when retrieving it (i.e. $price = (float)$custom['price'][0]; - which won't help with ordering in the first place), you can't 'adjust' the custom field data - it's always stored as text.

Having said that, you should simply remove the initial meta_value in your orderby argument:

$args['meta_key'] = 'price';
$args['orderby'] = 'meta_value_num';
$args['order'] = 'ASC';

Having used this exact argument set myself just yesterday, it works perfectly.

  • 1
    Very neat minimalistic solution!!! – Armando Dec 14 '18 at 16:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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