3

I have created a custom post type that I want to order by

  1. custom-field-1, which is boolean so its value is either 1 or 0, in DESC order (1 to 0)
  2. custom-field-2, which contains text and is supposed to be ordered ASC (A to Z)

First Question:

A more powerful ORDERBY-parameter was introduced in WordPress 4.0. Can this be made using the new ORDERBY functionality?

If not, second Question:

What's the best approach? How would I make a meta_query order the posts by custom-field-1 in descending order and then by custom-field-2 in ascending order?

Edit:

Or would it be an option to use two instances of WP_Query, one for the posts with custom-field-1 value = '1' and one for those with value 0 ?

I know this "order by multiple custom field values" has been discussed a lot here, but I did not find a similar question I could adapt when I was searching the site before.

2

Although the new orderby parameter is great in WP_Query, it does not support multiple orderby for multiple meta_key's.

I've went through a couple of scenarios and even went and digged into trac and make and came up with the following

None of the issues regarding this very problem have been answered. It also seems from those two links that there is an issue ordering by a meta_key and another field like post date for instance. I haven't tried this as yet.

I truelly think that you have two choices here without creating two queries.

  • hack using the posts_orderby filter as described by @s_ha_dum in his answer here

  • By making use of PHP ordering using usort. The idea here would be to sort your query by one meta_key and then take the returned posts array ($posts) and sort them by the second meta_key before the loop starts. You can either use the the_posts filter (just remember to remove the filter once done) or simply unset $posts in your template and set it with the reordered array of posts once done

| improve this answer | |
  • Thanks Pieter, that's useful information. Can the posts_orderby filter be combined or used within i.e. a pre_get_posts filter ? – okiedokey Oct 21 '14 at 10:16
  • For interest sake, were you able to get a working solution to this? – Pieter Goosen Oct 27 '14 at 8:13
  • Yes I did, I needed to use the function along with a search/filter plugin so it differs a little from a wp-only solution. I will edit my solution to make it independent from the plugin and post it soon. I can say the solution is strongly inspired by the link to @s_ha_dum's answer you posted – okiedokey Oct 27 '14 at 13:52
  • Great, looking forward to your solution. – Pieter Goosen Oct 27 '14 at 13:55
  • I didn't have the time to edit my solution to this question - but I accepted this answer because it led to my solution. – okiedokey Dec 11 '14 at 14:54

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.