How to add CORS headers for a WordPress website?

Sometimes, you need to add CORS headers to your WordPress website to use 3rd party services.

Adding CORS using the functions.php file

To add cors using functions.php file on WordPress, you can use the init hook and instruct it to add the needed headers using PHP as follow:

add_action('init', function (){   header('Access-Control-Allow-Origin: *');   header('Access-Control-Allow-Methods: GET, POST');   header("Access-Control-Allow-Headers: X-Requested-With"); });

Adding CORS using htaccess file

To add the same headers using the htaccess file, you use the following rules:

<IfModule mod_headers.c>    Header set Access-Control-Allow-Origin "*"    Header set Access-Control-Allow-Methods "GET, POST"    Header set Access-Control-Allow-Headers "X-Requested-With"  </IfModule> 

Something is unclear? Or need further explanation? Hit the chat icon on the right bottom side of the page, and let’s see how I can unriddle this specific matter ;)