Wordpress(ver 5.3.1)サイトのRSSフィードをAjaxで取得しようとしたときに
CORSでブロックされてしまった時の話。
ChromeのDeveloper Tool Consoleのエラー
※URLはサンプル例
Access to XMLHttpRequest at 'https://mydomain.com/?feed=rss2&_=xxxxxxxxxx'
from origin 'https://test.mydomain.com' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
対策
Wordpressのテーマのfunctions.phpに以下のコードを追加した。
functions.php
/**
* CORS対策
* Access-Control-Allow-Originヘッダの追加
*/
add_action('send_headers', 'cors_http_header');
function cors_http_header(){
header("Access-Control-Allow-Origin: https://test.mydomain.com");
}