Skip to content

Instantly share code, notes, and snippets.

@Shelob9
Created July 17, 2015 21:29
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Shelob9/87f9474df0f541e07383 to your computer and use it in GitHub Desktop.
<?php
/**
* Use * for origin
*/
add_action( 'rest_api_init', function() {
remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
add_filter( 'rest_pre_serve_request', function( $value ) {
header( 'Access-Control-Allow-Origin: *' );
header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
header( 'Access-Control-Allow-Credentials: true' );
return $value;
});
}, 15 );
/**
* Only allow GET requests
*/
add_action( 'rest_api_init', function() {
remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
add_filter( 'rest_pre_serve_request', function( $value ) {
$origin = get_http_origin();
if ( $origin ) {
header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) );
}
header( 'Access-Control-Allow-Origin: ' . esc_url_raw( site_url() ) );
header( 'Access-Control-Allow-Methods: GET' );
return $value;
});
}, 15 );
/**
* Only allow same origin
*/
add_action( 'rest_api_init', function() {
remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
add_filter( 'rest_pre_serve_request', function( $value ) {
header( 'Access-Control-Allow-Origin: ' . esc_url_raw( site_url() ) );
header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
header( 'Access-Control-Allow-Credentials: true' );
return $value;
});
}, 15 );
/**
* Only from certain origins
*/
add_action( 'rest_api_init', function() {
remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
add_filter( 'rest_pre_serve_request', function( $value ) {
$origin = get_http_origin();
if ( $origin && in_array( $origin, array(
//define some origins!
) ) ) {
header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) );
header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
header( 'Access-Control-Allow-Credentials: true' );
}
return $value;
});
}, 15 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment