How to parse rss feeds using WordPress built-in functions

How to parse rss feeds using WordPress built-in functions

These days a friend asked me about how can we parse RSS feeds using WordPress. So here we are! It’s pretty easy to do this by using fetch_feed (WordPress’ built-in function based on SimplePie).

function wcr_parse_feed($feed_url, $limit = 5) {
    // fetch feed
    $feed = fetch_feed($feed_url);

    if (is_wp_error($feed)) {
        return;
    }

    $max_items = $feed->get_item_quantity($limit);
    $items = $feed->get_items(0, $max_items);

    if (empty($items) || !is_array($items)) {
        return;
    }
	
    echo '<ul>';
        foreach ($items as $item) {
        ?>
        <li>
            <a href="<?php echo esc_url($item->get_permalink()); ?>">
                <?php echo esc_html($item->get_title()); ?>
            </a>
        </li>
        <?php
        }
    echo '</ul>';
}

Use case scenarios:

// 1. Parse last 5 posts from WPCrumbs (default cache lifetime: 12 hours)
wcr_parse_feed('https://wpcrumbs.com/feed/');

// 2. Parse last 10 posts
wcr_parse_feed('https://wpcrumbs.com/feed/', 10);
Leave a Reply

Get your fix of
all cool things WordPress

DigitalOcean hosting coupon 10$ coupon

for DigitalOcean hosting.
Sammy-approved.

Get this deal