Moreso a psuedo-code question than actual code. I have some custom post meta attached to attachments, and created a list table column for this meta. The meta is either 1, or null (not set), but I am trying to enable sorting for said column.
Is there a way to utilize meta_query
for WP_Query to essentially LEFT JOIN, where I get all values (1 or null), and then I can utilize orderby=meta_value_num
for ordering?
The obvious way it would work is hooking into posts_clauses, adding a JOIN, and doing the orderby as well – just curious if this would be possible while using direct WP_Query functionality!
Thanks.
You can use
pre_get_posts
with a callback:You can do it either way!
Using
posts_clauses
, manually write your JOIN statement (using $wpdb->prepare() – be safe!) , and add/customize theorderby
clause as well.Using
meta_query
there are a couple things needed. First, as kaiser mentions, you must userelation
withinmeta_query
in order for it to work. Second, even though meta_query is defined, you still need to specify themeta_key
argument, or else orderby=meta_value will not work. I assume this is because you can have multiple joins happening at once, which could be using different meta keys.Here is how I accomplished it: