Is there a way to set the user Role based on email domain

With this code, you will check during the registration the users email and attach the roles you want to:

<?php
add_action( 'user_register', 'wp234_set_role_by_email' );
function wp234_set_role_by_email( $user_id ){
    $user = get_user_by( 'id', $user_id );
    $domain = substr(
        strrchr(
            $user->data->user_email, 
            "@"
        ), 1
    ); //Get Domain

    $contributor_domains = array( 'gmail.com' );
    if( in_array( $domain, $contributor_domains ) ){
        foreach( $user->roles as $role )
            $user->remove_role( $role ); //Remove existing Roles
        $user->add_role( 'contributor' ); //Add role
    }

    $subscriber_domains = array( 'hotmail.com' );
    if( in_array( $domain, $subscriber_domains ) ){
        foreach( $user->roles as $role )
            $user->remove_role( $role ); //Remove existing Roles
        $user->add_role( 'subscriber' ); //Add role
    }

}
?>

If you want every other email domain to be a subscriber, you can simply go into Admin > Settings and declare the usual role as “Subscriber”. Or, you can use this instead of the $subscriber_domains-part:

<?php
    if( ! in_array( $domain, $contributor_domains ) ){
        foreach( $user->roles as $role )
            $user->remove_role( $role ); //Remove existing Roles
        $user->add_role( 'subscriber' ); //Add role
    }
?>

Leave a Comment