# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Users](https://wpide.com/library/category/users/)
- Tags: registration, roles, email
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/role-by-email-domain/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Assign a Role Based on the Email Domain" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
