Remove_role not working, gives “Call to undefined method stdClass::remove_role()”

It looks like your $user variable contents are not an instance of a WP_User class. You’ve got an error of stdClass, but you need the WP_User. Check what class the $user is the instance.

If you use the get_users() function, you should note one feature of this function described in the documentation:

Return value is an array of IDs, stdClass objects, or WP_User objects, depending on the value of the ‘fields‘ parameter.

  • If ‘fields‘ is set to ‘all’ (default), or ‘all_with_meta’, it will return an array of WP_User objects.
  • If ‘fields‘ is set to an array of wp_users table fields, it will return an array of stdClass objects with only those fields.
  • If ‘fields‘ is set to any individual wp_users table field, an array of IDs will be returned.