Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
<?php
/**
* Wordpress RSS 2.0 image enclosure.
*
* @param WP_Query $query The current WP_Query instance.
* @return WP_Query
*/
add_filter( 'pre_get_posts', 'feed_filter' );
function feed_filter( $query ) {
if ( $query->is_feed ) {
add_filter( 'rss2_item', 'feed_content_filter');
}
return $query;
}
/**
* How to add an enclosure to a wordpress RSS feed using the first image of the
* post [with its actual length attribute value].
*
* @param mixed $item Current feed item.
* @return mixed Feed item.
*/
function feed_content_filter( $item ) {
global $post;
$args = array(
'order' => 'ASC',
'post_type' => 'attachment',
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_status' => null,
'numberposts' => 1,
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$image = wp_get_attachment_image_src( $attachment->ID, 'large' );
$mime = get_post_mime_type( $attachment->ID );
}
}
if ( $image ) {
echo '<enclosure url="' . $image[0] . '" length="' . remote_file_size( $image[0] ) . '" type="' . $mime . '"/>';
}
return $item;
}
/**
* Get the remote file size.
*
* @see {@link http://www.w3bees.com/2013/03/get-remote-file-size-using-php.html}
* @author Resalat Haque
*
* @param string $url Remote file URL.
* @return int File size in bytes.
*/
function remote_file_size( $url ) {
// Get all header information
$data = get_headers($url, true);
// Look up validity
if ( isset( $data['Content-Length'] ) ) {
// Return file size
return (int) $data['Content-Length'];
}
}
@lfarah1971

This comment has been minimized.

Copy link

commented Jul 22, 2019

Hi. Sorry my terrible english. I past this code in main functions.php or in functions.php inside theme directory ?
thx

@DaveyJake

This comment has been minimized.

Copy link
Owner Author

commented Jul 23, 2019

I past this code in main functions.php or in functions.php inside theme directory ?

Paste inside /your-theme-directory/functions.php.

@lfarah1971

This comment has been minimized.

Copy link

commented Jul 23, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.