will-ashworth
8/15/2017 - 6:19 PM

Add posts images to all RSS feeds in Wordpress

Add posts images to all RSS feeds in Wordpress

== Changelog ==
 
= 1.0 =
* First public release
<?php
/*
Plugin Name: RSS feeds with images
Description: Add posts images to all RSS feeds
Author: Thomas Barthelet
Version: 1.0
*/

// register the specific media XML namespace (http://www.rssboard.org/media-rss)
function add_media_namespace() {
  echo 'xmlns:media="http://search.yahoo.com/mrss/"'."\n";
}
add_action( 'rss2_ns', 'add_media_namespace' ); // relevant Wordpress hook

// required function to encode URI with accentuated characters into valid XML URLs
function url_path_encode($url) {
    $path = parse_url($url, PHP_URL_PATH);
    if (strpos($path,'%') !== false) return $url; //avoid double encoding
    else {
        $encoded_path = array_map('urlencode', explode('/', $path));
        return str_replace($path, implode('/', $encoded_path), $url);
    }   
}

// the main function where images are added
function add_media_content() {
	global $post;
	if( has_post_thumbnail( $post->ID ) ) {
		$imgID = get_post_thumbnail_id( $post->ID );
		$arrSizes = array("thumbnail","medium","large"); // array of different sizes available of the same image
		// we add a media group with all the versions (sizes) of the same image
		echo "<media:group>";
		foreach ( $arrSizes as $size ) {
			$arrImg = wp_get_attachment_image_src($imgID, $size);
			if( is_array( $arrImg ) ) {
				echo '<media:content url="' . url_path_encode( $arrImg[0] )
				. '" width="' . $arrImg[1] 
				. '" height="' . $arrImg[2] 
				. '" medium="image" ' 
				. ($size=="medium" ? ' isDefault="true"' : '') // we set the medium size as default within the media group
				. ' />';
			}
		}
		echo "</media:group>";
		// we add the thumbnail image format as an additional media:content as well as a media:thumbnail element
		$thumb = wp_get_attachment_image_src( $imgID, 'thumbnail' );
		if( is_array( $thumb ) ) {
			echo '<media:content url="' . url_path_encode( $thumb[0] )
			. '" width="' . $thumb[1] 
			. '" height="' . $thumb[2] 
			. '" medium="image" />';
			echo '<media:thumbnail url="' . url_path_encode( $thumb[0] )
			. '" width="' . $thumb[1] 
			. '" height="' . $thumb[2] 
			. '" />';
		}
	}
}
add_action( 'rss2_item', 'add_media_content' ); // relevant Wordpress hook