Ryan Ryan - 1 year ago 121
PHP Question

How can I pull media:thumbnail from an RSS feed with SimplePie and fetch_feed()?

I have two separate WordPress installs – I will call one Site A, and the other Site B. I want to pull the feed from Site B onto Site A, using

. I also want to include a thumbnail image. WordPress doesn't include a thumbnail in the feed by default, so I created a custom feed, that includes the following:

<?php if(get_the_post_thumbnail()): ?>
<media:thumbnail url="<?php $image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'feed-thumb'); echo $image[0]; ?>" />
<media:content url="<?php $image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'feed-thumb'); echo $image[0]; ?>" medium="image" />

This seems to work, and it returns something like the following inside each :

<media:thumbnail url="http://www.site-b.com/wp-content/uploads/2013/01/thumbnail.jpg" />
<media:content url="http://www.site-b.com/wp-content/uploads/2013/01/thumbnail.jpg" medium="image" />

Now, I go back to Site A, and try to pull this feed using

<?php // Get RSS Feed(s)
include_once(ABSPATH . WPINC . '/feed.php');

// Get a SimplePie feed object from the specified feed source.
$rss = fetch_feed('http://www.site-b.com/custom-feed/');
if (!is_wp_error( $rss ) ) : // Checks that the object is created correctly
// Figure out how many total items there are, but limit it to 2.
$maxitems = $rss->get_item_quantity(2);

// Build an array of all the items, starting with element 0 (first element).
$rss_items = $rss->get_items(0, $maxitems);

if ($maxitems == 0) echo 'No items.';
// Loop through each feed item.
foreach ( $rss_items as $item ) :

if ($enclosure = $item->get_enclosure())
echo '<img src="' . $enclosure->get_thumbnail() . '" class="feed-thumb" />';

<p><?php echo esc_html( $item->get_description() ); ?>
<a href="<?php echo esc_url( $item->get_permalink() ); ?>"
title="<?php echo esc_html( $item->get_title() ); ?>">Continue Reading</a></p>

<?php endforeach; ?>

Everything works, except for the thumbnail. The title, the permalink, and the description are all returned correctly. However, the thumbnail does not return the URL. So, I am just left with:

<img src="" class="feed-thumb" />

How can I return the URL for the thumbnail image?

Thanks for reading this far.

Answer Source

Aaand, after pulling my hair out, it's because I forgot to include the Media RSS namespace in my custom feed. I simply included it in my opening <rss> tag and it worked:

<rss version="2.0" xmlns:media="http://search.yahoo.com/mrss">

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download