Skip to content

Instantly share code, notes, and snippets.

@Faisalawanisee
Last active February 10, 2019 21:44
Show Gist options
  • Save Faisalawanisee/d9583496fb7aac0bf595d5a7e6d84757 to your computer and use it in GitHub Desktop.
Save Faisalawanisee/d9583496fb7aac0bf595d5a7e6d84757 to your computer and use it in GitHub Desktop.
Allow Cross-domain requests
<?php
add_filter( 'wp_headers', array( 'eg_send_cors_headers' ), 11, 1 );
function eg_send_cors_headers( $headers ) {
$headers['Access-Control-Allow-Origin'] = get_http_origin(); // Can't use wildcard origin for credentials requests, instead set it to the requesting origin
$headers['Access-Control-Allow-Credentials'] = 'true';
// Access-Control headers are received during OPTIONS requests
if ( 'OPTIONS' == $_SERVER['REQUEST_METHOD'] ) {
if ( isset( $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] ) ) {
$headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS';
}
if ( isset( $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'] ) ) {
$headers['Access-Control-Allow-Headers'] = $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'];
}
}
return $headers;
}
@Faisalawanisee
Copy link
Author

add_action( 'init', 'handle_preflight' );

function handle_preflight() {
header("Access-Control-Allow-Origin: " . get_http_origin());
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Credentials: true");

if ( 'OPTIONS' == $_SERVER['REQUEST_METHOD'] ) {
    status_header(200);
    exit();
}

}

@Faisalawanisee
Copy link
Author

Info Here => WP-API/WP-API#144

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment