Wordpress - How to Add Image to Wordpress RSS-Feed with no Plug-in?
Here is a great example. How to display featured post thumbnails in WordPress feeds
paste this code snippet in your theme functions.php file
// display featured post thumbnails in WordPress feeds
function wcs_post_thumbnails_in_feeds( $content ) {
global $post;
if( has_post_thumbnail( $post->ID ) ) {
$content = '<p>' . get_the_post_thumbnail( $post->ID ) . '</p>' . $content;
}
return $content;
}
add_filter( 'the_excerpt_rss', 'wcs_post_thumbnails_in_feeds' );
add_filter( 'the_content_feed', 'wcs_post_thumbnails_in_feeds' );
Based on the notes here and many other resources I read, I came up with this solution specifically to work with Mailchimp RSS to Email converter with the feed from Wordpress. Their templates use the <media:content>
extension to the item
element to populate their image macro. This code goes in the functions.php of the theme.
// Add namespace for media:image element used below
add_filter( 'rss2_ns', function(){
echo 'xmlns:media="http://search.yahoo.com/mrss/"';
});
// insert the image object into the RSS item (see MB-191)
add_action('rss2_item', function(){
global $post;
if (has_post_thumbnail($post->ID)){
$thumbnail_ID = get_post_thumbnail_id($post->ID);
$thumbnail = wp_get_attachment_image_src($thumbnail_ID, 'medium');
if (is_array($thumbnail)) {
echo '<media:content medium="image" url="' . $thumbnail[0]
. '" width="' . $thumbnail[1] . '" height="' . $thumbnail[2] . '" />';
}
}
});
The choice of image size 'medium' can also be 'thumbnail' if you want one smaller.
I tried the selected answer and got a really big image in my feed. I would recommend adding an image size to the code.
// display featured post thumbnails in RSS feeds
function WPGood_rss_thumbs( $content ) {
global $post;
if( has_post_thumbnail( $post->ID ) ) {
$content = '<figure>' . get_the_post_thumbnail( $post->ID, 'thumbnail' ) . '</figure>' . $content;
}
return $content;
}
add_filter( 'the_excerpt_rss', 'WPGood_rss_thumbs' );
add_filter( 'the_content_feed', 'WPGood_rss_thumbs' );
I used 'thumbnail' for my feed, but 'medium' might work better for some sites.