Column sorting with emtpy meta values

The problem is that by setting the posts to be ordered by _start_event_datetime you’re creating the implicit assumption that the post will have that meta. This means the SQL query WordPress generates will only fetch posts of your custom post type with that meta.

There are two possible solutions to this:

  • Replace your current query with a slightly more complex meta query
  • Modify the SQL query to use an Outer Join rather than an Inner Join

I’ll show you how to do the first as it’s the most sensible way of doing this. The second option would make sense for more advanced sorting like sorting by multiple meta keys or taxonomies I’d recommend using the posts_clauses hook and looking into this blog post.

Using a meta query:

$query->set('meta_query',array(
    'relation'  => 'OR',
    array(
        'key'       => '_start_event_datetime',
        'compare'   => 'EXISTS'
    ),
    array(
        'key'       => '_start_event_datetime',
        'compare'   => 'NOT EXISTS',
        'value'     => 'bug #23268' // Allows WP-Librarian to run on pre-3.9 WP installs
    )
));
$query->set('orderby',   'meta_value_num');

This query gets all posts with or without the meta key. Note that the value for the NOT EXISTS condition is completely abritrary and is only there because of a bug in pre-3.9 WordPress.

Leave a Comment