How to Add Images to WordPress RSS Feeds and Caching
Adding featured images to your WordPress RSS feeds can make your content more engaging and visually appealing for subscribers, especially in feed readers that support images.
However, generating these images for every feed request can strain your server, particularly on high-traffic sites. This article presents a simple, performance-optimized WordPress code snippet that adds featured images to your RSS feeds while using caching to ensure fast load times.
// Main function to add featured image to RSS feeds
function rss_post_with_thumbnail( $content ) {
global $post;
if ( ! isset( $post ) || ! has_post_thumbnail( $post->ID ) ) {
return $content;
}
// Check for cached image HTML
$cache_key = 'rss_thumbnail_' . $post->ID;
$image_html = get_transient( $cache_key );
if ( false === $image_html ) {
// Generate image HTML if not cached
$image = get_the_post_thumbnail( $post->ID, 'medium', [ 'class' => 'rss-featured-image' ] );
$image_html = apply_filters( 'rss_post_thumbnail_html', '<p>' . $image . '</p>', $post->ID );
// Cache for 24 hours
set_transient( $cache_key, $image_html, 24 * HOUR_IN_SECONDS );
}
return wp_kses_post( $image_html ) . $content;
}
add_filter( 'the_excerpt_rss', 'rss_post_with_thumbnail' );
add_filter( 'the_content_feed', 'rss_post_with_thumbnail' );
// Clear cache when featured image is updated or removed
function rss_clear_thumbnail_cache( $post_id ) {
$cache_key = 'rss_thumbnail_' . $post_id;
delete_transient( $cache_key );
}
add_action( 'set_post_thumbnail', 'rss_clear_thumbnail_cache' );
add_action( 'delete_post_thumbnail', 'rss_clear_thumbnail_cache' );How the Code Snippet Works
This snippet enhances your WordPress RSS feeds by adding each post’s featured image before its content or excerpt, making your feeds more visually appealing. It checks if a post has a featured image and, if so, includes it in the feed, wrapped in a paragraph tag for consistent formatting. The image is set to the “medium” size for a balance of quality and performance and includes a CSS class for potential styling.
To optimize performance, the snippet uses WordPress’s transient API to cache the image HTML for 24 hours, reducing server load by reusing the cached version for subsequent feed requests. The cache automatically clears when a post’s featured image is updated or removed, ensuring the feed stays current.
This solution works for both full-content and excerpt-based RSS feeds, so your subscribers will see featured images in compatible feed readers, such as Feedly or Inoreader, without slowing down your site. To use it, add the snippet to your theme’s functions.php file or a custom plugin, and your RSS feeds will deliver images efficiently and reliably.
Written by Milan on 10th July 2025

