1

I can't believe I'm asking this question. It feels like such a simple method, yet I've poured over the WP pages and dozens of similar questions to no avail, so here it is...

I've got a WP_Query with the following, that just gets the last 5 posts:

$args = Array(
  'post_type' => 'post',
  'posts_per_page' => '5'
)

All I wanted to do was order the last 5 posts by the meta_value_num of the meta_key 'views'. But instead, when I put in something like the following, it grabs the top five most viewed posts ever.

$args = Array(
  'post_type' => 'post',
  'posts_per_page' => '5',
  'meta_key' => 'views',
  'orderby' => 'meta_value_num'
)

What am I doing wrong? I feel like this is endlessly frustrating, probably more so because I know the solution is almost certainly simple as pie.

  • Try 'order' = 'desc'. Actually you'd have to use 'orderby' = 'date' and 'order' = 'desc', but you need ordering by meta key and unfortunately you cannot use 2 orderby values! Or try the date orderby with a meta query. – Rutwick Gangurde Dec 30 '11 at 20:44
2

You need to sort in descending order so the last 5 posts will be on top. Just add 'order' => 'DESC' to your args.

$args = Array(
  'post_type' => 'post',
  'posts_per_page' => '5',
  'meta_key' => 'views',
  'orderby' => 'meta_value_num',
  'order' => 'DESC'
);

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.