Last active
November 20, 2023 07:54
-
-
Save csarigoz/df5e3ef54f44cd3aa5d5e982832490a6 to your computer and use it in GitHub Desktop.
Add thumbnail image of posts to WordPress RSS Feed -> Add to functions.php file of your theme
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Add namespace for media:image element used below | |
add_filter( 'rss2_ns', function(){ | |
echo 'xmlns:media="http://search.yahoo.com/mrss/"'; | |
}); | |
// insert the image object into the RSS item | |
add_action('rss2_item', function(){ | |
global $post; | |
if (has_post_thumbnail($post->ID)){ | |
$thumbnail_ID = get_post_thumbnail_id($post->ID); | |
$thumbnail = wp_get_attachment_image_src($thumbnail_ID, 'large'); | |
if (is_array($thumbnail)) { | |
// Parse the URL and remove query parameters | |
$parsed_url = parse_url($thumbnail[0]); | |
$clean_url = $parsed_url['scheme'] . '://' . $parsed_url['host'] . $parsed_url['path']; | |
echo '<media:content medium="image" url="' . $clean_url . '" width="' . $thumbnail[1] . '" height="' . $thumbnail[2] . '" />'; | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment