You have stuff on you WordPress website that you want to access from another site or mobile app? Well the easiest and most straight forward way would be an ajax request but BAMM you run into the cross domain error, ajax fails and your stuck. Have no fear this is a pretty simple thing to do but finding out HOW to get this relatively facile task done was an onerous wade through incomplete answers and confusing tutorials – for me at least. In the end I came to these easy steps by piecing together solutions from multiple sources. I hope this helps you! Note these steps are for windows but the overall process is the same for linux/mac. Also if you’re only interested in just getting info from one page then skip steps 1 and 2.
Step 1: Enable mod_header.c
(you can skip this step if you are using a remote server, mod_header.c should be enabled by default)
Go to where you have apache installed, do a search for a file called “httpd.conf”. Make a backup of it then open it in text editor, notepad works. Search for “mod_headers.so”, it should be around line 118 if you can see line numbers.
Remove the “#” from the line containing “mod_headers.so”.
#LoadModule headers_module modules/mod_headers.so
LoadModule headers_module modules/mod_headers.so
Step 2: Update .htaccess
Go to your wordpress site’s folder, open htaccess and add the following code block:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
This code block checks if mod_headers is enabled, then allows cross domain request from any site (replace the wildcard, “*”, with a specific site you want to give access too). The second line you add what headers are allowed. The third line is important, this is where you specify what types of requests your site will respond to. You can tweak these properties add a few others to get the best solution for your problem. You can find a complete list of fields and their purpose, as well as other info, here: w3.
Save your changes!
That should be it! However, remember that this allows cross domain access to every page of your site. If you want to allow access to only open page, say you want to set up an api, don’t use this solution, instead add these lines to the top of the api page’s php file.
header( "Access-Control-Allow-Origin: *" );
header( "Access-Control-Allow-Headers: origin, x-requested-with, content-type" );
header( "Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS" );