Adding a featured image to the WordPress RSS


By default, all sites that use WordPress have an automatic RSS feed, however, the feed does not have native support for displaying the featured images of posts.

Displaying them directly in the RSS can be useful in several cases, such as using the feed for an automatic newsletter of new posts, or to display them in a reader like Feedly. Fortunately, adding support for embedding the highlighted image is a relatively simple task.

For that, we will need to inject code into the functions.php file. Be sure to do this on a child theme to ensure that no changes are missed in a possible update to the parent theme. Also make a backup first, as functions.php is a sensitive file, and if something goes wrong, it can break your entire site.

Unraveling each line

We started the code by creating a function to add the image to the RSS. We use the variable $ post to get the information we need from the posts.

That done, we should inform WordPress that the $ output variable is empty, so we can insert only the information we need.

Right after, a check is made if the post has a highlighted image, and if the result is true, we store the image ID and the URL of the image in the “full” size.

If you prefer, you can use any of the other sizes that WordPress offers:

  • Thumbnail: 150x150px;
  • Medium: 300x300px;
  • Medium_large: 768x768px;
  • Large: 1024x1024px;
  • Full: The original size of the image;
  • Array (x, y): Replace X and Y with any value you want;

The WordPress Codex has even more details about the highlighted images. Depending on the theme used, there may still be other ways to add support for the images featured in the RSS. Search your theme’s documentation if this feature exists.

After capturing information about the image, we need to insert it into the output variable, using a specific XML tag that defines that content as a highlighted image.

After that, just add an action by calling the function created previously for the results to be applied. And ready!

The final result

The final result should look like this:

// Cria uma função
function add_rss_image() {
    global $post;
    // Procura se o post possui uma imagem destacada
    if ( has_post_thumbnail( $post->ID ) ) {
       $thumbnail_ID = get_post_thumbnail_id( $post->ID );
        $thumbnail = wp_get_attachment_image_src( $thumbnail_ID, 'full' );
            // Adiciona a tag media no XML com as informações de URL, altura e largura da imagem
        $output .= '

With this code added to your functions.php, your site should already have support for images featured in the RSS feed. With this, you can develop an email marketing strategy by sending your content automatically by email and with support for featured images. This can be great for your website’s SEO!

Do you have a tutorial on WordPress that you would like to see here? Leave in the comments ?

To the next!