Halloween Sale 15% off Ends in See the plans
PHP

Browser and CDN Caching for Feeds and Sitemaps

Sends cache headers on RSS feeds and XML sitemaps so feed readers, crawlers and CDNs can reuse them for an hour instead of making WordPress rebuild them on every request.

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

Code

// Seconds feeds and sitemaps may be cached.
$wpide_feed_cache_seconds = HOUR_IN_SECONDS;

add_action( 'template_redirect', function () use ( $wpide_feed_cache_seconds ) {
    if ( headers_sent() || is_user_logged_in() ) {
        return;
    }

    if ( is_feed() || get_query_var( 'sitemap' ) || get_query_var( 'sitemap-stylesheet' ) ) {
        header( sprintf( 'Cache-Control: public, max-age=%1$d, s-maxage=%1$d, stale-while-revalidate=60', (int) $wpide_feed_cache_seconds ) );
    }
}, 1 );

Notes

Lower $wpide_feed_cache_seconds if you publish many times an hour and want new posts to appear in feeds faster.

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.