I am building a movie archive. For each movie I am filling out the release dates for 3 countries, they're stored as custom fields (added via Pods)
Now, when listing the movies I would like to build an array and loop through each post to check if the fields have values, then compare the values and sort by the first date (oldest or least recent date). If none of the fields have values the posted date should be used for sorting. I am using this code for something similar
function orderby_additionaldate($query) {
if (! is_admin() && $query->is_main_query() && is_category( array( 2,57,530 ) ) || cat_is_ancestor_of(2, get_query_var('cat') ) && $query->is_main_query() && ! is_admin() || cat_is_ancestor_of(57, get_query_var('cat') ) && $query->is_main_query() && ! is_admin() || cat_is_ancestor_of(530, get_query_var('cat') ) && $query->is_main_query() && ! is_admin() ) {
if ( $query->query_vars ) {
$query->set( 'order', 'DESC' );
$query->set( 'meta_key', 'additional_date' );
$query->set( 'orderby', 'meta_value' );
}
}
}
add_action( 'pre_get_posts', 'orderby_additionaldate' );
Two things are missing from this:
- It's not comparing 3 meta key values (
release_f
,release_uk
, andrelease_us
). - It doesn't check if one of them is empty and use the posted date instead (it just sets the value of the empty ones to Jan 1 1970).