Skip to content

Instantly share code, notes, and snippets.

@supermethod
Created March 8, 2011 15:09
Show Gist options
  • Save supermethod/860385 to your computer and use it in GitHub Desktop.
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
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;
}
@GitMensch
Copy link

@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)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment