Let Other Sites Read Your Feeds With JavaScript
Sends a CORS header with your RSS and Atom feeds, so web apps, widgets and dashboards on other domains can load them with fetch() instead of hitting a browser error.
Opens WPIDE on
Code
// Sites allowed to read your feeds with JavaScript. '*' allows any site; or list origins such as 'https://app.example.com'.
$wpide_feed_cors_origins = array( '*' );
add_action( 'template_redirect', function () use ( $wpide_feed_cors_origins ) {
if ( ! is_feed() || headers_sent() ) {
return;
}
if ( in_array( '*', $wpide_feed_cors_origins, true ) ) {
header( 'Access-Control-Allow-Origin: *' );
} else {
$origin = isset( $_SERVER['HTTP_ORIGIN'] ) ? untrailingslashit( esc_url_raw( wp_unslash( $_SERVER['HTTP_ORIGIN'] ) ) ) : '';
$allowed = array_map( 'untrailingslashit', $wpide_feed_cors_origins );
header( 'Vary: Origin', false );
if ( '' === $origin || ! in_array( $origin, $allowed, true ) ) {
return;
}
header( 'Access-Control-Allow-Origin: ' . $origin );
}
header( 'Access-Control-Allow-Methods: GET, HEAD, OPTIONS' );
}, 1 );
Notes
Set the origins list to specific sites, such as your app's address, to allow only them; feeds are public, so '*' is safe for most sites.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.