Order Search Results Page by meta_value If no Value Return Remaining Results

You can accomplish this with multiple meta queries.

$query->set( 'meta_query', [
  'relation' => 'OR',
  'wpcf-start-date' => [
    'key' => 'wpcf-start-date',
    'compare' => 'EXISTS',
  ],
 'no-start-date' => [
    'key' => 'wpcf-start-date',
    'compare' => 'NOT EXISTS'
  ],
] );
$query->set( 'orderby', 'wpcf-start-date' );
$query->set( 'order', 'ASC' );

This will tell WP to create a query that will match every post, whether or not is has the key, setting it up as a LEFT JOIN, and then sorts on the value of that key, including those with NULL values.

Leave a Comment