Skip to content

Instantly share code, notes, and snippets.

@bostondv
Created February 29, 2016 21:44
Show Gist options
  • Select an option

  • Save bostondv/55c5acc008e87f18681b to your computer and use it in GitHub Desktop.

Select an option

Save bostondv/55c5acc008e87f18681b to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: WP REST API CORS
* Description: Fixes to enable <a href="http://www.html5rocks.com/en/tutorials/cors/">CORS</a> for the <a href="https://github.com/WP-API/WP-API">WP REST API</a>.
* Author: Boston Dell-Vandenberg
* Author URI: http://pomelodesign.com
* Version: 1.0.0
* Plugin URI: https://github.com/thenbrent/WP-API-CORS
*/
if ( ! class_exists( 'WP_API_CORS' ) ) :
/**
* @class WP_API_CORS
* @version 1.0
*/
final class WP_API_CORS {
/**
* @var The single instance of the class
* @since 1.0
*/
protected static $_instance = null;
/**
* Main Instance
*
* Ensures only one instance of the CORS headers is loaded and can be loaded.
*
* @since 1.0
* @static
* @return Main instance
*/
public static function instance() {
if ( is_null( self::$_instance ) ) {
self::$_instance = new self();
self::$_instance->setup_filters();
}
return self::$_instance;
}
/**
* A dummy constructor to prevent loading more than once.
*
* @see bbPress::instance()
* @see bbpress();
*/
private function __construct() { /* Do nothing here */ }
/**
* Init WooCommerce when WordPress Initialises.
*/
public function setup_filters() {
add_filter( 'rest_post_dispatch', array( &$this, 'send_cors_headers' ), 10, 3 );
}
/**
* Send headers to enable CORS
*/
public static function send_cors_headers( $result, $this, $request ) {
// Access-Control headers are received during OPTIONS requests
if ( 'OPTIONS' == $_SERVER['REQUEST_METHOD'] ) {
if ( isset( $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'] ) ) {
$result->header('Access-Control-Allow-Headers', $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']);
}
}
return $result;
}
}
endif;
WP_API_CORS::instance();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment