bloqhead
1/28/2016 - 4:46 PM

This function inserts a post's featured image above the excerpt content in WordPress' RSS feeds. Why? When our marketing team is tying thei

This function inserts a post's featured image above the excerpt content in WordPress' RSS feeds.

Why? When our marketing team is tying their clients' WordPress RSS feeds into HubSpot's email campaign feature, it only grabs the excerpt content, which has images stripped by default. This makes posts appear prettier and more uniform when HubSpot automagically inserts WordPress post content into an email.

<?php

/**
* Featured Image to RSS (refer to: http://goo.gl/BUHXIa)
*
* Author: Daryn St. Pierre
* Author-URL: http://bigseadesign.com
*
* Created: 2016-01-28
* Last-Modified: 2016-01-28
*
*/

function FeaturedToRSS( $content ) {
  global $post;
  $id = $post->ID;
  if ( has_post_thumbnail( $id ) ) {
    /* Clean images out of the existing content first */
    $CleanContent = preg_replace( '/<img[^>]+./', '', $content );

    /* Get the image src attribute */
    $ThumbSrc = wp_get_attachment_image_url( get_post_thumbnail_id( $id, 'thumbnail' ));

    /* Build the image */
    $ImageElement = '<img src="'. $ThumbSrc .'" style="display:block;margin-bottom:20px;width:100%;height:auto;" />';

    /* Insert the featured image above the content */
    $content = '' . $ImageElement . ' ' . $CleanContent;
  }
  return $content;
}

add_filter( 'the_excerpt_rss', 'FeaturedToRSS' );
add_filter( 'the_content_feed', 'FeaturedToRSS' );