Change role of all users with emails from specific domain when plugin is activated

I’d like to change the role of all users with a specific domain name (@example.com) to a custom role when my plugin is activated.

I found some code for doing it when a user registers and attempted to adapt it to my needs but it doesn’t seem to work. Nothing happens when I activate the plugin. The roles don’t change and I don’t get any errors popping up so I’m not quite sure what I’m doing wrong.

I’m still learning PHP so please forgive me if this doesn’t make sense.

Here’s my code:

function set_role_by_email( $user_id ){
$user = get_user_by( ‘id’, $user_id );
$domain = substr(
strrchr(
$user->data->user_email,
“@”
), 1
); //Get Domain

$custom_role_domains = array( ‘example.com’ );
if( in_array( $domain, $custom_role_domains ) ){
foreach( $user->roles as $role )
$user->remove_role( $role ); //Remove existing Roles
$user->add_role( ‘custom_role’ ); //Add role to user
}
}
register_activation_hook( __FILE__, ‘set_role_by_email’ );

Read more here:: Change role of all users with emails from specific domain when plugin is activated

Leave a Reply

Your email address will not be published. Required fields are marked *