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 '
- ';
foreach ($items as $item) {
?>
- get_title()); ?> '; }
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);