Created
March 8, 2011 15:09
-
-
Save supermethod/860385 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 - add to functions.php
This file contains hidden or 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
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@supermethod @DaveyJake Is there a reason to use an iteration (over the 1 entry array)?
I'd suggest to change it to something like
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?)
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)?