1

I'm Querying listings(custom post type) using WP_Query and ordering results by ACF meta field. The field contains price values with the currency symbol and comma separations like $100,000.

Here is the $args I'm passing to the WP_Query.

$args = array(
'post_type' => 'listing',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_key' => '_listing_price',
'orderby' => 'meta_value',
'order' => 'ASC'
);
$listing_query = new WP_Query($args);

This results:

$0 $0 $100,000 $150,000 $22,000 $320,300 $33,000 $359,000.

But I need result like this:

$0 $0 $22,000 $33,000 $100,000 $150,000 $320,300 $359,000.
Jan Sršeň
  • 1,045
  • 3
  • 23
  • 46
draz umar
  • 11
  • 2
  • 1
    Why you not store only numbers in this meta field and add currency symbol later? This will make order much simple. – marcelo2605 Mar 29 '19 at 19:48

1 Answers1

0

Ideally, you would just be storing the integer (or float) value, for instance: 0, 0, 22000, 323000, etc. This would allow you to add any currency symbols and formatting you'd like later, and it makes for easier sorting and manipulation.

So first of all, you should evaluate whether or not you can go through and do that (it's probably worth your while).

Barring that, you could try using the meta_value_num Orderby Parameter:

$args = array(
    'post_type'      => 'listing',
    'post_status'    => 'publish',
    'posts_per_page' => -1,
    'meta_key'       => '_listing_price',
    'orderby'        => 'meta_value_num',
    'order'          => 'ASC'
);

$listing_query = new WP_Query($args);

I'm not sure if it will work, however. The source shows it adding +0 to the meta query alias, but doesn't otherwise cast it - so I'm not sure how it handles the dollar signs, commas, and other characters.

The third alternative would be get your results like you are now, and then loop through them and reorder them manually based on the meta value. For a handful of listings it wouldn't add an enormous amount of overhead, but I'd avoid this approach at any sort of scale.

Xhynk
  • 13,513
  • 8
  • 32
  • 69
  • Alright I understand. But what if I'm not able to store data without currency symbol and commas? Would it be better to use the alternate approach of sorting listings later? If yes, then can you please suggest me an algorithm or approach of how can I sort them? Thank you! – draz umar Mar 29 '19 at 22:51