I'm building the sorting functionality for a custom post type, and I have a custom meta value for "Featured" posts. This value is set when you tick the checkbox, otherwise it is not set.
Using the default orderby=meta_value
with meta_key=featured
makes it so that the screen only displays posts that have the meta key. If they don't, they don't even appear.
I want it so if it is not set, they do appear, but they appear last. I assume I need to use meta_query
instead, but I couldn't get that to work either.
How do I allow empty, false, or non-existing meta keys in the WP_Query arguments?
My code is below. This is for sorting columns in the dashboard, so it is modifying the default WP Query args.
function featured_sortable_order( $vars ) {
if ( isset($vars['orderby']) && $vars['orderby'] == 'featured' ) {
$vars = array_merge( $vars, array(
'meta_key' => 'featured',
'orderby' => 'meta_value',
'order' => isset($vars['order']) ? $vars['order'] : 'asc',
) );
}
return $vars;
}
add_filter( 'request', 'featured_sortable_order' );