SimplePie / WordPress: Getting featured media images

If you find yourself wanting to read a WordPress RSS feed (or any feed really) and wanting to include the featured media image you can do it quite easily with a bit of code and a free plugin.

Firstly, on the WordPress side. WP doesn’t include featured media images in the feed by default, so you want to install this plugin: https://wordpress.org/plugins/rss-featured-image/

Next, you can use this code with SimplePie to read the posts, and specifically the media:

foreach ($blogposts->get_items(0,3) as $item) {
    $image = '';
    if ($enclosure = $item->get_enclosure())
    {
        $image = $enclosure->get_link();
    }

    $link = $item->get_permalink();
    $title = $item->get_title();
    $date = $item->get_date('j F Y | g:i a');
    
    ...
}