Since version 2.8, WordPress has included the SimplePie class at it’s core. For a while, SimplePie wasn’t being maintained by the developer, but the WordPress team took over and kept the class alive.
With the class now being at the core of WordPress, it can generate RSS and ATOM feeds. It also uses the cache of WordPress and, most importantly, that can be controlled via a hook.
I spoke previously about using caching when bringing in Twitter feeds.
This code operates slightly differently – calling different functions, but achieving a similar result, and potentially using functionality that will be updated more often and supported through future WordPress releases.
The code below is a snippet from a widget I’ve made that does something slightly different to a Twitter feed, but still, pulls content from an external XML file in WordPress.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
private function getXML(){ $url = $this->url; require_once (ABSPATH . WPINC . '/class-feed.php'); $feed = new SimplePie(); $feed->set_feed_url($url); $feed->set_cache_class('WP_Feed_Cache'); $feed->set_file_class('WP_SimplePie_File'); $feed->set_cache_duration(apply_filters('wp_feed_cache_transient_lifetime', 1, $url)); do_action_ref_array( 'wp_feed_options', array( &$feed, $url ) ); $feed->init(); $feed->handle_content_type(); if ( $feed->error() ) return new WP_Error('simplepie-error', $feed->error()); $this->feed = $feed->get_items(0, $this->totaltoget); } |
You can also update the default cache time through a filter. The standard of the cache time is set at 12 hours (43,200). The method WP_Feed_Cache_Transient(), parameter $lifetime is the import bit in the example above, and below. You can use the below filter either in a plugin or in the functions.php of the theme.
1 |
add_filter( 'wp_feed_cache_transient_lifetime', create_function( '$a', 'return 1800;' ) ); |
Image Credit: Schrottie
Comment or tweet @douglasradburn