Halloween Sale 15% off Ends in See the plans
PHP

Featured Images as media:content in RSS

Adds each post's featured image to the RSS feed as a media:content element, the format email newsletter tools and feed readers use to show a thumbnail.

Don’t have WPIDE yet? Install it on your site

Code

// Image size used in the feed.
$wpide_feed_image_size = 'large';

add_action( 'rss2_ns', function () {
    echo 'xmlns:media="http://search.yahoo.com/mrss/"' . "\n";
} );

add_action( 'rss2_item', function () use ( $wpide_feed_image_size ) {
    $post = get_post();

    if ( ! $post || ! has_post_thumbnail( $post ) ) {
        return;
    }

    $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post ), $wpide_feed_image_size );

    if ( ! $image ) {
        return;
    }

    $mime = get_post_mime_type( get_post_thumbnail_id( $post ) );

    printf(
        "<media:content url=\"%s\" medium=\"image\" width=\"%d\" height=\"%d\"%s />\n",
        esc_url( $image[0] ),
        (int) $image[1],
        (int) $image[2],
        $mime ? ' type="' . esc_attr( $mime ) . '"' : ''
    );
} );

Notes

Mailchimp, Feedly and most RSS-to-email services read this element. The image size is set at the top.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.