WordPress Meta Query Null Values Order

Generally, no, there is not a good way to achieve this if the sort order doesn’t produce things automatically in the order you need them. This is because WP_Query doesn’t allow for insertion of logic to say ‘order by fieldX except if $some_condition’

Somewhere, you’re going to have to write the logic for the order you want stuff to come out, and I think it makes sense to have this neatly in one place outside of where you query WP_Query and have your ‘presentation’ code.

However, as you may know, and for reference to others, there are a few ways to achieve what you want, in order that I’d recommend them for you:

  1. Write a new meta_value that stores the order

Hook into every place where this post type might get added or updated with a function that writes a sequential post meta value you can use to easily order in WP_Query. This gives you maximum flexibility to define the ordering using PHP code, and runs very rarely so is fast.

Pros: Fast, makes querying easy, use all features of WP_Query
Cons: Maybe some complicted PHP. Have to make sure you hook it into all the right places.

  1. Run and render multiple WP_Query’s for each case

This is sometimes useful if e.g. you have two cases you want to display in an order WP_Query won’t support, such as you have some NULL values that come out at the wrong end of the list. You’d need to query for the NULL values in one WP_Query, and run another with the stuff you want ordered and a condition to say ‘not the null values’:

Pros: Simplest presentation code
Cons: You might have to repeat UI presentation (the loop). Only supports simpler cases

  1. Get all posts into an array and then sort them how you want:

You could do a get_posts() to get everything, and then do some custom coding to sort them or output them in the order you want.

Pros: Exactly the order you want. Ordering code together with presentation code.
Cons: Complicated code, may require roll-your-own pagination

  1. Inject custom ORDER BY SQL

You can inject a custom ‘ORDER BY’ field into the WP_Query SQL using e.g. the 'posts_orderby' filter. These can include complicated SQL ORDER BY CASE statements that allow you to to write arbitrarily complex ordering statements, however this will involve getting into some complicated SQL

Pros: All PHP/presentation code is simplified
Cons: Involves writing complex SQL. Might break WP_Query in future