Adding a YouTube feed to a WordPress template

The built in WordPress function fetch_rss() makes it easy to pull in an RSS feed from any other site and display it on your own blog.  The function gives you convenient access to the raw data from the feed, so you can parse it in any way you like. For example, you might want to pull in the feed from a particular YouTube user and display their most recent 3 videos in your sidebar.

The first thing we want to do is visit the user’s page on YouTube to grab the feed URL for that person. It might be your own account, of course, but there’s no need to log in, and feeds are publically available from anyone’s account. Once on a user’s page, your browser should display an RSS icon: click on it and copy the URL of the feed. It will look something like this:

http://gdata.youtube.com/feeds/base/users/MontyPython/uploads?alt=rss&v=2&orderby=published&client=ytapi-youtube-profile

In this case I’ve grabbed the feed from a channel.

Next open up the WordPress template file for the page you want to display the content on. It might be ’sidebar.php’, for example. Wherever you want the videos to appear, you need to call the fetch_rss() function as described in the WordPress documentation.

<?php
// Get RSS Feed(s)
include_once(ABSPATH . WPINC . '/rss.php');
$rss = fetch_rss('http://gdata.youtube.com/feeds/base/users/MontyPython/uploads?alt=rss&v=2&orderby=published&client=ytapi-youtube-profile');
$maxitems = 3; //set number of items to display
$items = array_slice($rss->items, 0, $maxitems);
?>

In order to embed a YouTube Flash movie we could use the nested objects method, so we have valid HTML, and include some appropriate alternative content (in case the Flash fails to load for some reason). To set this up for each item, all we need from the feed is the ID of the video.

If we examine the RSS feed itself, we find that the video ID is contained in the final part of the ‘link’ element. To extract it, we’ll need to use a tiny bit of PHP to break up the URL string.

Of course we need to repeat this for each item in the feed, so we set up a loop like this:


<ul>
<?php if (empty($items)) echo '<li>No items</li>';
else foreach ( $items as $item ) : ?>
<div>
<?php
$youtubeid = strchr($item['link'],'='); //split off the final bit of the URL beginning with '='
$youtubeid = substr($youtubeid,1); //remove that equals sign to get the video ID
//Now embed the flash:
?>
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="320" height="265">
<param name="movie" value="http://www.youtube.com/v/<?php echo $youtubeid ?>&hl=en&fs=1" />
<!--[if !IE]>-->
<object type="application/x-shockwave-flash" data="http://www.youtube.com/v/<?php echo $youtubeid ?>&hl=en&fs=1" width="320" height="265">
<!--<![endif]-->
<p><a href="http://www.youtube.com/v/<?php echo $youtubeid ?>">View movie&raquo;</a></p>
<!--[if !IE]>-->
</object>
<!--<![endif]-->
</object>
</li>
<?php endforeach; ?>
</ul>

This method is pretty easy to adapt for any type of RSS feed you might want to use: Vimeo, Slideshare, Twitter, etc. Of course there are loads of WordPress plugins that can help you embed this stuff, but sometimes a plugin doesn’t give you exactly the output you need, and it’s helpful to be able to parse the feed yourself.

14 Comments

  1. [...] выполнял данную функцию я не нашел, но зато нашел отличное решение с помощью встроенных RSS-функций Wordpress [...]

  2. Hmm, would you not suggest using the FlashSatay method instead (http://alistapart.com/articles/flashsatay)?

    Also I would suggest making the above standards compliant:
    –> should be

    And you can escape the url:
    “&hl=en&fs=1″ should be “&hl=en&fs=1″

    Chris.

  3. Hi Chris

    I’m using code based on the the SWFObject method (http://code.google.com/p/swfobject/). It has a couple of advantages over Satay (e.g. no need for a container movie) and validates fine. I don’t mind IE conditional comments, personally.

    Good point about properly encoding the amphasand. I should fix that.

  4. And hello to my Russian readers, by the way!

    I’m always amazed anyone reads this stuff.

  5. Hi there,

    I found this through google and I think it’ll be helpful. I wanted to run my idea past you and see if you think it is feasible:

    Having videos post as posts automatically when the rss feed updates, pulling the description, title, and video id from the rss feed.

    Think it is possible?

    Thanks!

  6. @Benjamin Jones: I think this would be extremely difficult and well beyond the scope of what I’m discussing in this post. You would need to get WP to automatically check for a new item via RSS and publish a new post – all without you logging in or doing anything.

  7. [...] seguire questo ottimo tutorial (in inglese) e aggiungere il relativo codice al tema, niente di più facile Tag Technorati: [...]

  8. Thanks a ton for the code. Using it along with Exec-PHP and Smart Youtube, I put together a page on Wordpress (my own install) that always retrieves the latest 10 videos and embeds them on my site. The end result is here – http://www.themintonfamily.com/site/?page_id=1102

    Thanks again,

    Bill Minton

  9. Thanks very much for this code. It works perfectly as written above in a sidebar text widget if you are using Exec PHP. I am implementing it on a site I’m developing. How would you parse and display the video title as well?

  10. @live music fan: echo $item['title'] for the title.

  11. Thank you very much! This whas very helpfull.

  12. This is great — thank you! There are a lot of widgets for this functionality, but sometimes you just need the control of setting it up yourself. :-)

  13. Thx a lot .. this is what i was looking for… prase feeds my self… just found this is so simple…. thanks again.

Leave a comment