Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fabioricali/712d01b1a1193a4aa5f238a14caf24af to your computer and use it in GitHub Desktop.
Save fabioricali/712d01b1a1193a4aa5f238a14caf24af to your computer and use it in GitHub Desktop.
How to add an enclosure to a wordpress RSS feed using the first image of the post [with its actual length attribute value] - add to functions.php
add_filter( 'pre_get_posts', 'feed_filter' );
function feed_filter( $query ) {
if ( $query->is_feed ) {
add_filter( 'rss2_item', 'feed_content_filter');
}
return $query;
}
function feed_content_filter() {
global $post;
if( has_post_thumbnail( $post->ID ) ) {
$image_id = get_post_thumbnail_id( $post->ID );
$url = wp_get_attachment_image_url( $image_id, 'large' );
$file_type = wp_check_filetype( basename( $url ) );
$image_type = $file_type['type'];
$attach = wp_get_attachment_metadata( $image_id );
$upload_dir = wp_upload_dir();
$length = 0;
$file = $upload_dir['basedir'] . '/' . $attach['file'];
if ( file_exists( $file ) ) {
$length = filesize( $file );
}
echo "<enclosure url=\"{$url}\" length=\"$length\" type=\"{$image_type}\" />";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment