I have two queries that result in id-arrays that I merge into a common array which, in turn, has all the posts I need from the two post types (posts, events). However, in the sorted list I would like to not use the event's publication "date" for sorting, but the metadata field "event-date". However, posts don't have that field so they should be sorted using the standard "date". Basically, the result should be a list that is sorted by a post-object's meta field event-date when present for the post and the standard publication date if not.
I remember having done something similar a long time ago using SQL directly by creating a common key for sorting. This similar older question also resorts to SQL in the end - Mix post date with post meta value using WP_Query
But remembereing "fallback" arguments in the wp-query arguments, I was wondering if this can also be achieved using wp_query directly. Alas, so far my attempts have been unlucky. The code below is what I've come up with googling for ideas - the meta query is in there so posts without the meta-key are also included.
These query args do return "some order", but a weird one. It's certainly not what I'm looking for. For the few last years I did not have to resort to directly querying SQL in WP, because wp_query had become sufficiently powerful, maybe this problem can also be addressed using the class, even if not by me?
Thanks for every tip!
$args = array( 'post__in' => $all_ids, 'meta_query' => array( 'relation' => 'or', array( 'key' => '_event_date', 'compare' => 'EXISTS', ), array( 'key' => '_event_date', 'compare' => 'NOT EXISTS', ) ), 'orderby' => array( 'meta_value_num' => 'DESC', 'date' => 'DESC'), 'order' => 'DESC', );