title: Wordpress assign user role based on username
body: <p>I want to assign <strong>user role based on username</strong> so if you type BATMAN as username you will be assigned SUPER HERO role:</p>
  <p>I've done it based on email but how do I do this based on username?</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>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-&gt;data-&gt;user_email, 
              "@"
          ), 1
      ); //Get Domain
  
      $contributor_domains = array( 'gmail.com' );
      if( in_array( $domain, $contributor_domains ) ){
          foreach( $user-&gt;roles as $role )
              $user-&gt;remove_role( $role ); //Remove existing Roles
          $user-&gt;add_role( 'contributor' ); //Add role
      }
  
      $subscriber_domains = array( 'hotmail.com' );
      if( in_array( $domain, $subscriber_domains ) ){
          foreach( $user-&gt;roles as $role )
              $user-&gt;remove_role( $role ); //Remove existing Roles
          $user-&gt;add_role( 'subscriber' ); //Add role
      }</code></pre>
  </div>
  </div>
  </p>