0

[Answered by Roberthue - I was sorting by meta_value instead of meta_value_num]

I've created a WP_Query that does the following:

  • Grabs a list of businesses for sale
  • Orders them by a meta query, taken from the URL using get_query_var
  • Uses a sort order from the query var
  • Checks a meta_query to ensure the sale item is active

For the most part, it works. The meta query properly distinguishes between active and inactive posts, the sort will ascend and descend, there's just one problem... the data sorts like this in descending order:

  • 99999
  • 749000
  • 350000
  • 300000
  • 2700000
  • 249000
  • 247000
  • 2000000
  • 1536000
  • 145000

Welp, that's not right...

Here's my query args:

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$listing_args = array(
    'post_status' => 'publish',
    'post_type' => 'business',
    'posts_per_page'         => '12',
    'meta_key' => get_query_var('orderby'),
    'orderby' => 'meta_value',
    'order' => get_query_var('order'),
    'paged' => $paged,
    'meta_query' => array( // Only grab active listings
        array(
            'key' => 'property_active',
            'value' => 1,
            'compare' => '='
        ),
    ),
);

// The Query
$businesses = new WP_Query( $listing_args );

Far as I can tell, that's not wrong either. The fields themselves are generated by ACF and delegated "numeric".

I'm at a complete loss for ideas.

3
  • 2
    If your meta values are numeric then you should use orderby meta_value_num instead of meta_value. codex.wordpress.org/Class_Reference/…
    – Robert hue
    Commented Sep 22, 2014 at 9:51
  • @Roberthue Dang, thanks. I knew it was going to be something simple. Logic at 3am is bad mmkay. Commented Sep 22, 2014 at 9:59
  • That's great! I also add this below if anyone else having same issue.
    – Robert hue
    Commented Sep 22, 2014 at 10:09

1 Answer 1

2

I also added this here for someone else having same issue.

If your meta values are numeric then you should use orderby meta_value_num instead of meta_value.

As mentioned in codex.

  • meta_value - Note that a meta_key=keyname must also be present in the query. Note also that 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). Use meta_value_num instead for numeric values.

  • meta_value_num - Order by numeric meta value (available with Version 2.8). Also note that a meta_key=keyname must also be present in the query. This value allows for numerical sorting as noted above in meta_value.

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.