Add WordPress featured image to RSS feed

自作多情 提交于 2019-12-03 07:32:04
Ash

I often have to create custom feeds for MailChimp, and find that a lot of the time I have to make somewhat 'hacky' changes like putting custom values into the limited standard fields that MailChimp supports.

Because of this I like to use the method described at Yoast ( http://yoast.com/custom-rss-feeds-wordpress/ ) to create a page that outputs a custom RSS feed.

There are couple of tweaks to make in order to get the featured image included as a field that MailChimp will recognise.

Firstly, you need to add the Media RSS namespace, which I usually do by adding to the opening <rss> tag:

<rss version="2.0" xmlns:media="http://search.yahoo.com/mrss">

Then in order to include the featured image inside the item:

<?php if(get_the_post_thumbnail()): ?>
    <media:content url="<?php echo wp_get_attachment_url(get_post_thumbnail_id($post->ID)); ?>" medium="image" />
<?php endif; ?>

If you need to specify a particular image size to include, you'll need to use this code inside the item instead:

<?php if(get_the_post_thumbnail()): ?>
    <media:content url="<?php $image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'imageSize'); echo $image[0]; ?>" medium="image" />
<?php endif; ?>

You can then grab this in MailChimp using the *|RSSITEM:IMAGE|* or *|FEEDITEM:IMAGE|* merge tags.

Scott Hildebrand

There seem to be plenty of examples of how to add the image to the top of the content in the feed, but not too many where you're creating a new tag. One potential issue is that creating a custom tag or something similar won't be a valid RSS format. If you're creating an XML document for your own usage it doesn't matter so much if the feed validates. Here's what I did, and you should easily be able to modify it slightly for the MailChimp use case.

In functions.php add (inside the theme folder: wp-content/themes/{your-active-theme-folder}):

function insertImageRSS() {
  global $post;
  preg_match("/(http:\/\/.*(jpg|jpeg|png|gif|tif|bmp))\"/i", get_the_post_thumbnail( $post->ID, 'thumbnail' ), $matches);
  return $matches[1];
}

In the wp-includes/feed-rss2.php ( I used the enclosure tag, but haven't yet done the filesize calculation, so I used a placeholder ):

<?php if (get_the_post_thumbnail( $post->ID, 'thumbnail' ) != '') { ?><enclosure <?php echo 'url="' . insertImageRSS() . '"'; ?> length="1000" type="image/jpeg" /><?php } ?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!