Assign a Role Based on the Email Domain
Gives people who register with certain email domains a different role automatically, for example staff at your company become Contributors.
Opens WPIDE on
Code
// Email domain => role.
$wpide_domain_roles = array(
'example.com' => 'contributor',
);
add_action( 'register_new_user', function ( $user_id ) use ( $wpide_domain_roles ) {
$user = get_userdata( $user_id );
$domain = $user ? strtolower( substr( strrchr( $user->user_email, '@' ), 1 ) ) : '';
if ( isset( $wpide_domain_roles[ $domain ] ) && get_role( $wpide_domain_roles[ $domain ] ) && ! get_role( $wpide_domain_roles[ $domain ] )->has_cap( 'promote_users' ) ) {
$user->set_role( $wpide_domain_roles[ $domain ] );
}
} );
Notes
Only applies to self-registration, never to accounts created by an administrator. Avoid roles that can publish or manage other users.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.