-
-
Save supermethod/860385 to your computer and use it in GitHub Desktop.
function feedFilter($query) { | |
if ($query->is_feed) { | |
add_filter('rss2_item', 'feedContentFilter'); | |
} | |
return $query; | |
} | |
add_filter('pre_get_posts','feedFilter'); | |
function feedContentFilter($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="" type="'.$mime.'"/>'; | |
} | |
return $item; | |
} |
2019-06-26: I've updated my forked gist to include proper file formatting with DocBlocks as well.
Came across the snippet that will retrieve the image `length` aka filesize using the `src` attribute value. Originally posted on W3Bees:
/**
* Get Remote File Size
*
* @param sting $url as remote file URL
* @return int as file size in byte
*/
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'];
}
}
Just change the length
attribute on Line 30
to length="' . remote_file_size($image[0]) . '"
and you're all set!
This was immensely helpful! Thank you! 👍
March 2019: still works like a charm. Awesome!
@supermethod @DaveyJake Is there a reason to use an iteration (over the 1 entry array)?
I'd suggest to change it to something like
$attachments = get_posts($args);
if ($attachments && $attachments[0]) {
$image = wp_get_attachment_image_src($attachments[0]->ID, 'large');
$mime = get_post_mime_type($attachments[0]->ID);
echo '<enclosure url="'.$image[0].'" length="" type="'.$mime.'"/>';
}
But in general the wp-include has a function for this: function rss_enclosure()
at its current place "src/wp-includes/feed.php" since version 3.7, claiming it is in since version 1.5.0, therefore I wonder if the underlying problem that this gists solves is "no enclosure key available so take the first attachment instead".... Wouldn't it be useful to hack feed.php to fallback to the attachments?
BTW: How to make an "enclosure key available" from the UI?
I guess applying the standard filter would be just adding the following to functions.php (is it?)
add_filter('the_excerpt_rss', 'rss_enclosure');
add_filter('the_content', 'rss_enclosure');
This still leaves one question - is there any possibilty to add the filter by URI (or otherwise) on a wordpress,com site (which prohibits the editing of function.php)?
Great stuff 👍