7
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WordpressのAccess-Control-Allow-Originヘッダ追加

Posted at

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");
}
7
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?