1

My issue

Hello, some time ago:

  • I had the regular post and the custom evento post types;
  • the evento post type had a ev_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 regular post_date, while for evento it had to be ev_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:

  1. I hooked a function to post_save telling it to update_post_meta a post meta called order_date for each post type, with post_date's value if post and ev_data_out's value if evento;
  2. I filtered pre_get_posts with a function that conditioned to if (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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.