How do I fetch feed info from cache instead of directly from feed?

I have been using SimplePie to fetch items from a feed and display them on an aside section on my site. I didn't notice before, but this was increasing the load time of the site by over 10 seconds. The reason I believe is that I haven't been using cache, so every time someone entered the site they would access/download the feed all over again.

So I set up a cronjob as the documentation told me. Creating update_simplepie_cache.php in public_html. This worked and the cron job has created a file in public_html/cache/.

The question is - how do I change my current markup to fetch info from the cache instead of directly from the feed?

Here's the markup I have been using (this is in front-page.php)

?php 
require_once  (ABSPATH . WPINC . '/class-feed.php');
$feed_url = 'feed://nordiccoffeeculture.com/feed/';
$feed = new SimplePie();
$feed-set_feed_url($feed_url);
$feed-init();
?

?php foreach ($feed-get_items(0, 6) as $item): ?
    div class="col-lg-2 col-md-2 col-sm-4 col-xs-12 nordic-blog-item"
        ?php 
        $rss_image = ($item-get_item_tags('', 'image'));

        if ($rss_image) { ?
            a class="recent-blog-img-link" href="?php print $item-get_permalink(); ?"img srcset="?php print $rss_image[0]['data']; ?"//a?php 
        } else { ?
            !-- takes the first image of the RSS item content, and displays it --
            a class="recent-blog-img-link" href="?php print $item-get_permalink(); ?"img srcset="?php get_first_image_url($item-get_content()); ?"//a?php 
        }?
        h3a href="?php print $item-get_permalink(); ?"
        ?php print $item-get_title(); ?/a/h3
        ?php echo shorten($item-get_description(), 50); ?br
        span class="nordic-date"?php echo date_i18n('F j, Y', $item-get_date('U')); ?/span
    /div
?php endforeach; ?

Topic simplepie feed cache Wordpress

Category Web


You could simply use fetch_feed() that implements it's own extension of SimplePie_Cache:

$feed = new SimplePie();
...
$feed->set_cache_class( 'WP_Feed_Cache' );
...
$feed->set_feed_url( $url );
...
$feed->set_cache_duration( apply_filters( 
    'wp_feed_cache_transient_lifetime', 12 * HOUR_IN_SECONDS, $url ) );

that caches the feeds with set_transient().

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.