Enable CORS on JSON API Wordpress Enable CORS on JSON API Wordpress wordpress wordpress

Enable CORS on JSON API Wordpress


I've used a few different WordPress API's - but for those of you using the 'official' WP-API, I had much trouble with this CORS --- and what I found was that between the .htaccess approach and a few others I stumbled upon... adding this to your theme functions.php worked best.

function add_cors_http_header(){    header("Access-Control-Allow-Origin: *");}add_action('init','add_cors_http_header');

Be sure not to use any combinations of these ( .htaccess, header.php, api.php, functions.php ) as it will be angry at you.


Ok I finally figured out an easy way...

You just have to add:

     <? header("Access-Control-Allow-Origin: *"); ?>

On the file api.php, this file is located in wp-content/plugins/json-api/singletons/api.php

I hope it helps more people with the same problem!


Before the response is sent to the browser, we can run two action hooks and insert a new header():

do_action("json_api", $controller, $method);do_action("json_api-{$controller}-$method");

The first one runs on every method, and the second one is to target specific methods. Here's an implementation of the first one, with a commented way to find the second:

add_action( 'json_api', function( $controller, $method ){    # DEBUG    // wp_die( "To target only this method use <pre><code>add_action('$controller-$method', function(){ /*YOUR-STUFF*/ });</code></pre>" );    header( "Access-Control-Allow-Origin: *" );}, 10, 2 );