Altering WordPress Feed’s Cache Lifetime with ‘wp_feed_cache_transient_lifetime’ filter

It a well-known fact that when you publish an article not just in WordPress but also in most blogging platforms and CMS, the feed get updated automatically with the article. But do you know editing an already published article doesn’t auto-update the feed?

By default, WordPress cache feed or rather the cached feed has a lifetime of 43200 seconds, equivalent to 12 hours. There isn’t an option to purge the cached feed.

Say, you published an article and later discovered a typographical error was made. You swiftly edited and corrected the mistake. But do you know that the correction didn’t reflect in your WordPress feed?
The effect of this is, a reader who subscribed to your feed will receive and read the article containing the error because the feed will only get updated in 12 hours time.

You can actually reduce or increase the default cache lifetime simply by hooking a function that returns an integer (time in seconds) into the wp_feed_cache_transient_lifetime filter.


function return_cache_time( $seconds )
{
// change the default feed cache recreation period to 2 hours
return (int) 7200;
}

//set feed cache duration
add_filter( 'wp_feed_cache_transient_lifetime', 'return_cache_time');

The above code snippet will cache the feed for 7200 seconds (2 hrs). setting it 0 actually might disable feed caching.

To use the code, you might want to add it to your theme’s functions.php or create a plugin with it.

Also, say you are building a plugin that displays content from RSS feed using fetch_feed function, you can set the cache lifetime by adding the wp_feed_cache_transient_lifetime filter before the fetch_feed code and afterward removing it like so:


function return_cache_time( $seconds )
{
// change the default feed cache recreation period to 2 hours
return (int) 7200;
}

// adds the filter to set cache lifetime
add_filter( 'wp_feed_cache_transient_lifetime' , 'return_7200' );

$feed = fetch_feed( $feed_url );

// remove the filter to reset the cache lifetime to default value
remove_filter( 'wp_feed_cache_transient_lifetime' , 'return_cache_time' );
Don’t miss out!
Subscribe to My Newsletter
Invalid email address