WordPress: Check if a User Has a Specific Role

The default current_user_can() and user_can() functions are adequate for checking if a user belongs to a role, but I find the function names confusing.  Also, those functions check both roles and capabilities, which seems inefficient if one only needs to check the role.

This function does one thing only: check if a user belongs to a role.

function myprefix_user_has_role($user, $rolename) {
  if ( !is_a($user, 'WP_User') ) {
    $user = get_userdata( $user );
  }
  if ( !$user ) {
    return false;
  }

  foreach($user->roles as $role) {
    if (strtolower($rolename) === strtolower($role) ) {
      return true;
    }
  }
  
  return false;
}

A common usage is to check if a user an administrator, so this function works along with the above function to do just that:

function myprefix_is_admin($user = null) {
  if ($user == null) {
    $user = get_current_user_id();
  }
  return myprefix_user_has_role($user, 'administrator');
}