How to add CORS headers for a WordPress website?

On some occasions, you need to add CORS headers to your WordPress website to use 3rd party services. The following snippet will allow you to add CORS headers without having to change the server’s configuration:
function add_cors_headers(){
  header('Access-Control-Allow-Origin: *');
  header('Access-Control-Allow-Methods: GET, POST');
  header("Access-Control-Allow-Headers: X-Requested-With");