0

I have this custom query:

query_posts(  
  array ( 
    'orderby' => 'rr_recommends_count',
    'meta_key' => 'rr_recommends_count',
    'order' => 'DESC',
  )
);

Which orders the posts like this:

9, 8, 7, 6, 5, 4, 3, 2, 11, 10, 1 etc.

I see that the problem is that the meta_value field has a type of longtext.

How can I fix the sort without changing the meta_value field type?

2 Answers 2

2

First of all, never ever use query_posts. It breaks the main function and all plugins and functions relying on the main query object. For custom queries, use WP_Query or get_posts if aren't looking to paginate the query

As for the following line

'orderby' => 'rr_recommends_count',

I can tell you that rr_recommends_count is an invalid value to the orderby parameter. Suspect that this is actually the key name, and the values are all numerical in that key, so you would use the meta_value_num value to the orderby parameter which is a valid value

'orderby' => 'meta_value_num',

Please see Order and Orderby Parameters in WP_Query

2
  • Replaced it with: 'orderby' => 'meta_value_num' and works. I still don't understand why rr_recommends_count is invalid to the orderby parameter. orderby accepts strings and arrays. Commented Jun 22, 2015 at 12:46
  • 1
    I think you are misunderstanding the complete parameter. The new array syntax you are talking about is the new syntax where you can order by more than one value, say title and date. To fully understand thisn you will need to dig into a very messy WP_Query class which runs over 3000 lines of code :-) Commented Jun 22, 2015 at 12:49
0

please try this:

$args = array(
    'orderby'   => 'meta_value_num',
    'meta_key'  => 'rr_recommends_count',
     'order'   => 'DESC');
$query = new WP_Query( $args );
1
  • 1
    Why must he use try this. Please add a proper explanation to your code and how it works. Commented Jun 22, 2015 at 11:45

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.