My issue
Hello, some time ago:
- I had the regular
post
and the customevento
post types; - the
evento
post type had aev_data_out
custom field; - the search result loop had to return a list of posts from both the post types (if relevant for the search), ordered by date;
- for
post
the considered field when ordering had to be the regularpost_date
, while forevento
it had to beev_data_out
.
An example to clarify better.
These posts' dates:
PT "post" PT "evento"
----------------------- -------------------------
post_date = 2019-10-10 ev_data_out = 2020-11-10
post_date = 2017-03-12 ev_data_out = 2018-12-01
had to return a list ordered this way:
Results
--------------
2020-11-10
2019-10-10
2018-12-01
2017-03-12
My solution
Since my knowledge of Wp Query was (and is) still basic but I needed a fast implementation, I came out with this:
- I hooked a function to
post_save
telling it toupdate_post_meta
a post meta calledorder_date
for each post type, withpost_date
's value ifpost
andev_data_out
's value ifevento
; - I filtered
pre_get_posts
with a function that conditioned toif (is_search && !is_admin())
and setting$query -> set('meta_key', 'order_date');
and$query -> set('orderby', 'meta_value');
My question
So far I never had to retouch this stuff for it seems to work perfectly.
My question is, rather, if there is a method inherently better in Wordpress terms, i.e. if -with a better knowledge of the Wp Query, and of the meta queries in particular- I could get something more efficient and less DB-consuming.
N.b. I wish to understand things and not only to copy/paste, so an answer like "yes, study Wp Query better and you'll get the same result" would be perfectly fine for me!
Thanks!