Close

April 24, 2018

How to Add Featured Images to Your WordPress RSS Feed

If you want to add featured images to your WordPress RSS feed (as enclosures), here’s what to do. First, you need to hook into the RSS feed as each item is built. This hook will do that:

<?php
add_action( 'rss2_item', 'rss_add_featured_image' );

Next, in our callback function, we need to check if the current post has a featured image. We’ll use has_post_thumbnail() for that:

<?php
if ( function_exists( 'has_post_thumbnail' ) && has_post_thumbnail( $post->ID ) ) {
    // do stuff here   
}

No, we need to get the URL of the featured image if it does exist. Here, we’ll need to run through a couple steps like this:

<?php
$attachment_id = get_post_thumbnail_id($post->ID);
$featured_image = wp_get_attachment_image_src( $attachment_id, 'post-thumbnail' );
$url = $featured_image[0];

Enclosures require you set not only the URL, but also the length of the file (in bytes) and the MIME type. Here’s how to do that:

<?php
$length = filesize(get_attached_file($attachment_id));
$type = get_post_mime_type($attachment_id);

And, finally, we can out put the enclosure using printf():

<?php
printf('<enclosure url="%s" length="%s" type="%s" />', $url, $length, $type);

This can all be inside a plugin or in your theme’s functions.php file. Although, I’d recommend using a plugin so if you change themes, you don’t have to transfers this code over to your new theme. And, if you’re ready to get serious about building WordPress plugins, then enroll in my WordPress plugin course. Inside, you build a contact form plugin, but, more importantly, you’ll learn fundamental WordPress plugin-building skills like creating custom post types, adding shortcodes, adding custom columns to the post table and more. You can learn more here.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.