Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bcreeves/3a31247509b79ac456bc8145e26962ad to your computer and use it in GitHub Desktop.
Save bcreeves/3a31247509b79ac456bc8145e26962ad to your computer and use it in GitHub Desktop.
Wordpress sort by custom field date if it exists, otherwise sort by pub date.
<?php
$paged = get_query_var('paged', 1);
$cat = get_query_var('cat', '');
$args = [
'post_type' => 'post',
'post_status' => 'publish',
'paged' => $paged,
'cat' => $cat,
'meta_query' => [
'relation' => 'OR',
'event_clause' => [
'key' => 'end_date',
'value' => date('Ymd', strtotime('+1 week')),
'compare' => '<=',
'type' => 'DATE',
],
[
'key' => 'end_date',
'compare' => 'NOT EXISTS',
],
],
'orderby' => 'event_clause date',
'order' => 'DESC',
];
$query = new WP_Query($args);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment