Change the cache interval

On the last page we learned how to display a simple list of links from external RSS feed on our WordPress site, we also learned that this function automatically caches the result to prevent WordPress from fetching the feed on each request. As I said on the last page the default lifetime on this cached results is 12 hours (or 43200 seconds), that means the output on your WordPress site will change only 2 times a day.

To change this time we need to write a simple function that returns a integer value, this value will represent the number of seconds the cache will live before WordPress fetches the feed again. You can name this function what you want, but notice that it takes 1 parameter ($seconds), but doesn’t actually make use of it. You should find a suitable value for this, too low and you risk fetching the feed too often, this will cause a little delay for your visitors, and if the feed you are using is not yours, the owner may not be too happy about you fetching his feed every 5 minutes. If the value is too high, your data won’t be as fresh as you might would like it to be.

function custom_feed_time($seconds) {
    return 3600; // 1 hour
}

[adsense-banner]

Now that we have this simple function we need associate this function with a filter, so our fetch_feed function will get this our new value instead of the default. We need to do this at the beginning of our code, in line 2

include_once(ABSPATH.WPINC.'/feed.php');
add_filter( 'wp_feed_cache_transient_lifetime' , 'custom_feed_time' );
$parser = fetch_feed('http://www.webdevcorner.net/feed');
remove_filter( 'wp_feed_cache_transient_lifetime' , 'custom_feed_time' );

Here we added the filter with the name of our custom function as parameter number 2, then we run fetch_feed and remove our filter when we are done with it to prevent it from interfering with some other plugin or functionality.