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

Question

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.

0
Line One 3 months 2022-05-23T20:17:51-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse