Quick N Dirty – Enable CORS in WordPress 4

15th January 2015 - QuickAndDirty, wordpress

Hello again, another Quick n Dirty here, this time for wordpress (on Windows).

Specifically, if you are using the JSON API for wordpress and you find that you’re getting the following error from a JSON call.

 XMLHttpRequest cannot load No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is therefore not allowed access.

If you have a site which is on a different domain, a standard install of the json plugin will not allow you to communicate with your wordpress site via json.

The solution is to add a header to the wp-json plugin code. Bear in mind that an update to the plugin will most likely mean you will need to reapply this fix.

Open up the wp-content/plugins/json-rest-api/lib/class-wp-json-posts.php

At around line 190, add the header, as below, underneath the “Last- Modified” header;

 $response->header( 'Last-Modified', mysql2date( 'D, d M Y H:i:s', get_lastpostmodified( 'GMT' ), 0 ).' GMT' );

For other REST end points, open up the appropriate class file and add the line in what looks like a similar place. I have faith in you!


Until, next time.