Automatically replace members with an empty user role with another role

277 Views Asked by At

I want to move all members whose user role is empty to the default role. Is there a code about it?

1

There are 1 best solutions below

1
On BEST ANSWER

Yes, first you can use wp_get_users_with_no_role() function to get all users with no role (This function returns user ids). Then you can pass that user_id $u = new WP_User( $user_id ); and set the new role $u->set_role( 'subscriber' );. Here you can also find list of user Roles and Capabilities.

Paste that in your theme functions.php file.

add_action('init', function(){
    $users = wp_get_users_with_no_role();
    if( !empty($users) ){
        foreach($users as $user_id) {
            $u = new WP_User( $user_id );
            $u->set_role( 'subscriber' );
        }
    }
}, 10);

This code isn't tested so let us know if that worked!