Sorting posts that has a meta value first then the rest of the posts

I would suggest you when you are updating meta values with 1 update rest with 0.
I mean set the key in all posts with 1 or 0 to avoid the complex query.

You can still do it with a simple script. It will check if key doesn’t exist then update it with 0. So your current code will work like charm.

OR

You can use compare with NOT EXISTS

$meta_query = array(
    'relation' => 'OR',
    array(
        'key' => 'mp_micropub_accredited',
        'value' => 1
    ),
    array(
        'key' => 'mp_micropub_accredited',
        'compare' => 'NOT EXISTS'
    )
);
$query->set( 'meta_query', $meta_query );
$query->set( 'orderby', 'meta_value_num' );

Note: This solution will only work with WP >= 3.9 as NOT EXISTS only works with 3.5 and greater and there was a bug with NOT EXISTS which has been fixed in 3.9!

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)