Add featured image to your WordPress RSS Feed

In this post we'll look at how you can add a post's featured image to your WordPress RSS feed. 

Googling how to do this will present several plugin options, but this can actually be achieved with a few lines of code, and means you don't have to install third party code on your site. 

Programatically adding featured image to your WordPress RSS feed

Override the rss feed template

Firstly, in the functions.php we want to override the default rss2 feed (note you could also override a different rss template such as atom if you wanted to). Add the following code to functions.php:

remove_all_actions( 'do_feed_rss2' );
add_action( 'do_feed_rss2', 'post_feed_rss2', 10, 1 );
function post_feed_rss2( $for_comments )
{
    $rss_template = get_template_directory() . '/feeds/feed-rss2.php';

    if( get_post_type() == 'post' and file_exists( $rss_template ) )
    {
        load_template( $rss_template );
    }
    else
    {
        do_feed_rss2( $for_comments );
    }
}

This code is modified from the WordPress documentation, however in their example get_query_var can return an array and so the above fails. In the above example this has been replaced with get_post_type.

Next, copy the file from wp-includes/feed-rss2.php (again note the other templates if you want to override a different template), and paste this file into a new feeds directory inside your theme directory. 

Modify the template

Now that we have control over the template, we need to add in the featured image to a new tag. This can be achieved by placing the following code within the while loop, I'd recommend placing it after the closing 'link' tag (on version 4.4.1 you would add the code on line 85):


<?php if ( has_post_thumbnail() ) : ?>
    <media:content url="<?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id(), 'thumbnail' );
        echo $thumb['0']; ?>" medium="image" />
<?php endif; ?>

Notice we use the media:content tag to conform with the RSS specification.

Test the RSS feed

Check your feed now (default should be available on yoursite.com/feed), and you should see the updated tag. Keep in mind the feeds are often cached, so you might want to update a recent post to trigger the feed to update.

Sign Up

NEXT: Show multiple property values in a form select drop down in Symfony

How to show multiple property values in a form select drop down in Symfony.

comments powered by Disqus
Sign Up

Popular Tags

350x250

Need a web developer?

If you'd like to work with code synthesis on your next project get in touch via the contact page.