is_feed ) {
add_filter( 'rss2_item', 'feed_content_filter');
}
return $query;
}
/**
* Add an enclosure to a wordpress RSS feed using the first image of the post
* [with its actual length attribute value] via {@see 'pre_get_posts'}.
*
* @global WP_Post|object $post Current post object.
*/
function feed_content_filter() {
global $post;
$args = array(
'order' => 'ASC',
'post_type' => 'attachment',
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_status' => null,
'posts_per_page' => 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 );
$size = remote_file_size( $image[0], $attachment->ID );
}
}
if ( ! empty( $size ) && is_wp_error( $size ) ) {
echo '' . esc_html( $size->get_error_message() ) . '';
} elseif ( isset( $image[0] ) ) {
echo '';
}
}
/**
* Get the remote file size.
*
* @author Resalat Haque
* @link http://www.w3bees.com/2013/03/get-remote-file-size-using-php.html
*
* @param string $url Remote file URL.
* @param int $attachment_id Fallback in case URL is not valid.
*
* @return int File size in bytes.
*/
function remote_file_size( $url, $attachment_id = 0 ) {
// Default file size will always be 0.
$size = 0;
// Make sure URL is valid.
if ( wp_http_validate_url( $url ) ) {
// Get all header information.
$data = get_headers( $url, true );
// Look up validity.
if ( isset( $data['Content-Length'] ) ) {
// Return file size.
$size += (int) $data['Content-Length'];
return $size;
}
} elseif ( $attachment_id !== 0 ) {
// If we're here, it's because we know the file exists but not the URL.
$file = get_attached_file( $attachment_id );
// Return file size.
$size += (int) filesize( $file );
return $size;
}
return new WP_Error( 'invalid_image', __( "The image URL `{$url}` was invalid or not found." ) );
}