I need a way to sort the posts on my tag and category archives according to the event date (if it exists) OR post date (if it doesn't).
I have a combined archive for events and posts, but want to list events based on their event_date meta, instead of the date they were posted.
I know I need to update the query to add an "orderby" argument, but can't think of the best way to structure a query argument to get the results I need.
My thinking is that I need to do something like:
foreach($posts as $post) {
$event_start = get_post_meta($object_id, 'event_start', TRUE);
if($event_start) {
$event_start = strtotime($event_start);
$list_timestamp_map[$object_id] = $event_start;
} else {
$post_date = get_the_date('Y-m-d H:i:s',$object_id);
$post_date = strtotime($post_date);
$list_timestamp_map[$object_id] = $post_date;
}
}
arsort($list_timestamp_map);
}
Basically:
- Check if the "event_start" field has a value
- If it does, get/use that date
- If it doesn't, get/use the post date
- Sort the posts according to that list
But how do I query/compare/sort an existing archive based on a combination of custom field data and post date?
I can't do this:
function rtt_event_sorting( $query ) {
if( $query->is_main_query() && ( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {
$query->set('orderby','meta_value');
$query->set('meta_key','event_start');
$query->set('orderby','DESC');
return $query;
}
}
add_filter( 'pre_get_posts', 'rtt_event_sorting' );
Because if I add a "meta_key" argument it'll return posts based on whether that meta exists or not, not based on its value if it exists and the post date if it doesn't.
I'm probably overthinking it, but what's the best solution here?