This tutorial will show you how to set WordPress user roles based on their email address.
This could be really helpful if you're looking to classify users based on the organizations that they're coming from. For example, student email addresses all end with a .edu extension, government email addresses all end with a .gov extension, and many companies utilize a standard domain across all of their employees. Therefore, if you're looking to have users sign up on your website and be classified into a specific user role based on their email address, you can do that with the following code snippet, sourced from stackexchange.com.
In this basic example, anybody with a @isotropic.co email address is registered as an editor. Anybody with a @nyu.edu email address becomes registered as a contributor.
<?php
add_action( 'user_register', 'iso_set_role_by_email' );
function iso_set_role_by_email( $user_id ){
$user = get_user_by( 'id', $user_id );
$domain = substr(
strrchr(
$user->data->user_email,
"@"
), 1
); //Get Domain
$editor_domains = array( 'isotropic.co' );
if( in_array( $domain, $editor_domains ) ){
foreach( $user->roles as $role )
$user->remove_role( $role ); //Remove existing Roles
$user->add_role( 'editor' ); //Add role
}
$contributor_domains = array( 'nyu.edu' );
if( in_array( $domain, $contributor_domains ) ){
foreach( $user->roles as $role )
$user->remove_role( $role ); //Remove existing Roles
$user->add_role( 'contributor' ); //Add role
}
}
?>
Code language: HTML, XML (xml)
Easily add this PHP snippet to your site with Advanced Scripts or Code Snippets. Just past in, hook into the init, and it will work like a charm.
Customizing this snippet is also very easy. All you need to do is replace the email domains with your custom domains, and then change the user role if you want to change that. You can even use a custom user role if you have added it to your site (“student” for example).
Change this email: $contributor_domains = array( '<strong>nyu.edu</strong>' );
Change this role: $user->add_role( '<strong>contributor</strong>' ); //Add role
Code language: PHP (php)
Thank you for sharing. Exactly what I needed !
If we want the role to apply to several domain names, is this ok ?
array( 'domain1.com','domain2.com', 'domain3.com')
Hi Irwin-
How did you get this to work and how did you test? I'm new to this.
I went ahead and pasted the code as is, updated the domains and what not. Refreshed user page but do not see any changes.
Would you mind helping me?
Hello, what do you mean by hook it into the init?