1

I'm working on a rather large and old Wordpress project where someone has previously used query_posts all over the place. For this reason, I'm unwilling to change those method calls. I'm not the maintainer of the site, I'm doing a quick fix.

Each post in question has a field called our_date, which represents a date and a time, and title. The customer wants the posts ordered by title, but so that the future posts appear first in the list and all the past dates at the bottom.

This is what I'm working with right now:

'orderby' => array('date' => 'ASC'),

What's the best way to accomplish this custom sorting of results from query_posts?

3
  • So two lists of posts? Those yet to be be published, sorted by title, followed by those already published, sorted by title? If so, that's cake and pie. Regardless of whether the site uses query_posts in other places, what prevents you from using WP_Query class here on this page?
    – jdm2112
    Sep 13, 2016 at 16:06
  • "Future" ? It's not default for WP to even query future posts on front end. For starters how is that implemented and what full queries look like? Do you mean that date should be from custom field, not actual post date? Is title native or custom field as well?
    – Rarst
    Sep 13, 2016 at 18:06
  • @Rarst: I didn't know that, it explains a lot I guess. our_date is a custom field, but title is the native field.
    – damd
    Sep 14, 2016 at 8:47

2 Answers 2

0

I don't think this is doable in a single WP API query. You just don't sort whole set with single logic, you have logic changing halfway. I don't think even SQL can express this.

It is hard to advise without seeing specific circumstances (such as counts, pagination involved and so on), but my first thought would be to split this into two queries:

  1. "Future" posts (meta query for date field in future, order by title)
  2. "Past" posts (meta query for date field in the past, order by title)
0

Out of the box, wordpress queries do not have the ability to sort by two keys. I am far from being a mysql person, but I am sure that you can write such a query, which means that you can use the relevant query related filters to adjust the sql query generated by wordpress to be the desired one.

But I would probably just switch the use of query_posts to proper use of wp_query, and sort the resulting posts in PHP. The performance hit should be negligible (virtually zero if page caching is used) and the code a little more straight forward.

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.