Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.