0

For example if a user registered with the email domain:

[email protected]

They will be set as a contributer.

but if any other email such as

[email protected]

they will be set as a subscriber?

Thank you!

1 Answer 1

2

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
    }
?>
2
  • How would I use a wildcard to replace hotmail.com? Thank you.
    – jackdh
    Commented Mar 20, 2015 at 13:04
  • updated the code to respond to your question :) Commented Mar 20, 2015 at 13:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.