2

I simply want to get the list of users with get_users() but filtering on the field user_status=0 so the spam and unactivated users are removed from the list.

This does not work:

get_users( 'user_status=0&orderby=ID&order=desc&number=' . $limit );

This doesn't work either:

$new_users = get_users( [
    'orderby'     => 'ID',
    'order'       => 'DESC',
    'user_status' => [ 0 ],
    'number'      => $limit
] );

Neither does this:

    $new_users = get_users( [
    'meta_key'     => 'user_status',
    'meta_value'   => '0',
    'meta_compare' => '=',
    'orderby'    => 'ID',
    'order'      => 'DESC',
    'number'     => $limit
] );

So... what would be the correct way to do this?

1 Answer 1

2

The user_status field has long been no longer used in core, so maybe that's why there is no argument that will filter the users by their user_status value?

However, you can use the pre_user_query hook to alter the user query's SQL command, i.e. to add something like a AND user_status = 0 into the WHERE clause.

So for example, you can add this into your theme's functions.php file, and then just set the user_status argument, e.g. get_users( 'user_status=0' ) (like you did in your first example):

add_action( 'pre_user_query', 'my_pre_user_query' );
function my_pre_user_query( $query ) {
    if ( isset( $query->query_vars['user_status'] ) ) {
        $query->query_where .= " AND user_status = " . (int) $query->query_vars['user_status'];
    }
}

Alternatively, you could just make a custom instance of WP_User_Query, then set the WHERE condition the same way it's set above (i.e. via direct modification on the $query_where property), like so:

$query = new WP_User_Query;

$query->prepare_query( [
    'orderby' => 'ID',
    'order'   => 'DESC',
    // don't set user_status
    'number'  => $limit,
] );

// Now modify the WHERE clause.
$query->query_where .= " AND user_status = 0";

// Then run the SQL command.
$query->query();

$users = $query->get_results();
var_dump( $users );
1
  • 1
    Splendid. I love both solutions. In my case I like the first one best because it makes all get_users() lists capable of dealing with a user_status argument instantly.
    – Floris
    Commented Jul 22, 2021 at 20:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.