Support » Fixing WordPress » Change Role based on email domain name

  • I would like to institute a membership based on a domain name (i.e. a company). So everyone who is in example.com will have a higher role (say, contributor), as opposed to someone who is NOT in example.com, who will have only subscriber role.

    Is there plugin (preferred) that is available?

    Or more simply, has anyone done this?

    ben

Viewing 3 replies - 1 through 3 (of 3 total)
  • I’m not sure if there are any plugins that do this, but it would not be too tricky to write something. If you hook into the wp_login & wp_logout actions you could add the desired role when a user logs in and then remove it when they logout. Something along these lines could do what you want.

    disclaimer: the code below is untested and may have errors in it.

    class role_domain_swapper {
    
        public function __construct() {
    
            $this->do_hooks();
            $this->domain_role_map[ 'domain_A' ] = 'contributor';
            $this->domain_role_map[ 'domain_B' ] = 'subscriber';
    
        }
    
        public function add_role( $user_login, $user ) {
    
            global $unique_name_remapped_user_roles;
            $unique_name_remapped_user_roles[] = $user->ID;
            $user->add_role( $this->domain_role_map[ $_SERVER['SERVER_NAME'] ] );
        }
    
        public function remove_role() {
    
            $current_user = wp_get_current_user();
    
            global $unique_name_remapped_user_roles;
            if( in_array( $current_user->ID, $unique_name_remapped_user_roles ) ) {
    
                $current_user->remove_role( $this->domain_role_map[ $_SERVER['SERVER_NAME'] ] );
            }
        }
    
        private function do_hooks() {
    
            add_action( 'wp_login', array( $this, 'add_role' ), 10, 2 );
            add_action( 'wp_logout', array( $this, 'remove_role' ) );
        }
    
        private $domain_role_map;
    
    }

    If you do not want to add the above code as a class, you could use a code snippet plugin (https://en-gb.wordpress.org/plugins/search.php?q=code+snippets) to add the code without fear of the changes being overwritten due to a theme update.

    Add following code in your theme functions.php file and when a user register having email domain name “example.com” then his role is automatically become Contributor.

    add_action( 'user_register', 'cedcommerce_update_role' );
    
    function cedcommerce_update_role($user_id)
    {
     $user_data = new WP_User($user_id);
     if(isset($user_data->data))
     {
      $userdata = $user_data->data;
      $user_mail = $userdata->user_email;
      if (strpos($user_mail, 'example.com') !== false)   //Change the domain name by your domain name
      {
       $user_data->set_role('contributor');
      }
     }
    }

    Thanks

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Change Role based on email domain name’ is closed to new replies.