Allow the Administrator Role Only for Company Email Addresses
Refuses to give the administrator role to accounts whose email address is not on one of your approved domains, whether set from the profile screen, the Add User screen or a bulk role change.
Opens WPIDE on
Code
// Email domains allowed to hold the administrator role.
$wpide_admin_domains = array( 'example.com' );
$wpide_domain_ok = function ( $email ) use ( $wpide_admin_domains ) {
$domain = strtolower( (string) substr( strrchr( (string) $email, '@' ), 1 ) );
return in_array( $domain, array_map( 'strtolower', $wpide_admin_domains ), true );
};
add_action( 'user_profile_update_errors', function ( $errors, $update, $user ) use ( $wpide_domain_ok ) {
if ( isset( $user->role ) && 'administrator' === $user->role && ! $wpide_domain_ok( $user->user_email ) ) {
$errors->add( 'wpide_admin_domain', '<strong>Error:</strong> Administrators must use an approved company email address.' );
}
}, 10, 3 );
add_action( 'set_user_role', function ( $user_id, $role, $old_roles ) use ( $wpide_domain_ok ) {
$user = get_userdata( $user_id );
if ( 'administrator' !== $role || ! $user || $wpide_domain_ok( $user->user_email ) ) {
return;
}
static $busy = false;
if ( $busy ) {
return;
}
$busy = true;
$fallback = $old_roles && 'administrator' !== reset( $old_roles ) ? reset( $old_roles ) : get_option( 'default_role', 'subscriber' );
$user->set_role( 'administrator' === $fallback ? 'subscriber' : $fallback );
$busy = false;
}, 1, 3 );
Notes
Set $wpide_admin_domains to your own domains before activating; existing administrators are not changed.
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.