Allow CORS for RSS feed in wordpress

This article simply shows you how to resolve CORS issue when access RSS feed of wordpress from outside world.

Add below code to the end of your function.php file

add_action( 'pre_get_posts', 'add_header_origin' );

function add_header_origin() {
	if (is_feed()){
		header( 'Access-Control-Allow-Origin: *' );
	}
}   

Above code will allow anyone access your RSS feed, if you need certain domains to be allowed, update * with domains, eg:

add_action( 'pre_get_posts', 'add_header_origin' );

function add_header_origin() {
	if (is_feed()){
		$origin = get_http_origin();
		$allowed_origins = [ 'https://your.site' ];
		if($origin && in_array( $origin, $allowed_origins )){
		  header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin )  );	
		}
	}
}

Scroll to Top