Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.