Sort users by meta key value even if meta key not present for all users

Only some users have a specifice meta_key some_metakey associated with their ID. The following args successfully orders users with a specified role by some_metakey but only those with that meta_key.

Can anyone point the direction to change the args to include ALL users with a specified role even if they do not have the some_metakey meta_key?

$args = array(
    'role__in' = 
    [ 
        'role1', 
        'role2', 
        'role3', 
        'role4' 
    ],
    'order' = 'DEC', 
    'meta_key' = 'some_metakey',
    'orderby' = 'meta_value'
);
$users = get_users( $args );

Topic order user-meta sort Wordpress

Category Web


WordPress roles are stored in $wpdb->usermeta with wp_capabilities meta key, however, as a serialized array (see maybe_serialize).

So you could actually make a group of meta queries, with OR as the relation, to find users with any role of your 4 defined roles, OR users having a certain meta key and value:

Please note that in you change the roles, make sure to calculate the character length for that role, and place that length after s: characters (e.g; for administrator, the meta value search will be s:13:"administrator";b:1, and s:10:"subscriber";b:1 for subscriber users).

$args = array(
    'meta_query' => [ 
        'relation' => 'OR',
        [
            'key' => 'wp_capabilities',
            'value' => 's:5:"role1";b:1',
            'compare' => 'LIKE',
        ],
        [
            'key' => 'wp_capabilities',
            'value' => 's:5:"role2";b:1',
            'compare' => 'LIKE',
        ],
        [
            'key' => 'wp_capabilities',
            'value' => 's:5:"role3";b:1',
            'compare' => 'LIKE',
        ],
        [
            'key' => 'wp_capabilities',
            'value' => 's:5:"role4";b:1',
            'compare' => 'LIKE',
        ],
        [
            'key' => 'some_metakey',
            'value' => 'YOUR VALUE HERE',
            'compare' => '=', // or any other comparator, see WP_Meta_Query docs
        ],
    ],
    // 'order' => 'DESC', 
    // 'meta_key' => 'some_metakey',
    // 'orderby' => 'meta_value'
);

$users = get_users( $args );

Now for the ordering, that can get difficult - if you do not limit your queries then you could just do a usort order on the result array, otherwise, look into WP_User_Query, they have some hooks to use to manipulate the class state and hence the SQL query.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.