conditions
podcast
UPDATE: Looking for more functionality and an easier installation method? Check out my WordPress plugin: Youtube Feeder It's based on this code and has a LOT more features WordPress shortcodes are great. They let you perform complex operations or display dynamic content with just a tiny bit of text in any page or post. I [...]"/>
jobsguidelines
Home > Programming, Web Development > WordPress: Embed Youtube Feed With a Simple Shortcode

WordPress: Embed Youtube Feed With a Simple Shortcode

forum
feed
contentaddressinternational

UPDATE: Looking for more functionality and an easier installation method?

Check out my WordPress plugin: Youtube Feeder

It's based on this code and has a LOT more features


WordPress shortcodes are great. They let you perform complex operations or display dynamic content with just a tiny bit of text in any page or post.

I recently needed a way to embed the most recent videos from a Youtube channel (very dynamic information) in a WordPress page, so I decided to write a shortcode for it.

The code is actually pretty simple. Just add the following to your theme's functions.php file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function youtube_feed_shortcode($atts)
{
    // Defaults:
    extract(shortcode_atts(array(
            'user' => 'flamadiddle86', // youtube user
            'limit' => 5, // maximum number of videos
            'height' => 385, // video height
            'width' => 480 // video width
        ), $atts));
    $data = @json_decode(file_get_contents('http://gdata.youtube.com/feeds/api/users/'.$user.'/uploads?alt=json'), TRUE);
    $counter = 0;
    $content = '<div class="youtubefeed">';
    foreach($data['feed']['entry'] as $vid)
    {
        $url = $vid['media$group']['media$content'][0]['url'];
        $title = $vid['title']['$t'];
        $ycontent = $vid['content']['$t'];
        $content.= '<object width="'.$width.'" height="'.$height.'">'.
            '<param name="movie" value="'.$url.'"></param>'.
            '<param name="allowFullScreen" value="true"></param>'.
            '<param name="allowscriptaccess" value="always"></param>'.
            '<embed src="'.$url.'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="'.$width.'" height="'.$height.'"></embed></object>'.
            '<div class="youtubetitle">'.$title.'</div>'.
            '<div class="youtubecontent">'.$ycontent.'</div>'."\n";
        $counter++;
        if($counter == $limit)
        {
            break;
        }
    }
    $content .= '</div>';
    return $content;
}

add_shortcode('youtubefeed', 'youtube_feed_shortcode');


And it couldn't be easier to use. The videos you see below were embedded simply by putting this code in the post:

1
[youtubefeed]





Neytiri Attacks
Mia "Stay" -ing
We've only been teaching this trick for a couple days. She learns fast.
Mia playing tug of war
Mia, our 11-week-old weimaraner, playing tug of war with a friend's dog.
Mantis kung fu
rm -rf /*
I've always wanted to do this.



The shortcode is completely configurable. The following code would have resulted in the exact same output:

1
[youtubefeed user="flamadiddle86" limit="5" height="385" width="480"]

You can change any option as needed.

You might have noticed the code gives each element a particular class to make it CSS friendly. All you have to do is add CSS rules for three classes: .youtubefeed, .youtubetitle, and .youtubecontent.

My stylesheet looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.youtubefeed {
    margin: 10px;
    text-align: center;
}

.youtubetitle {
    font-size: 1.6em;
    font-weight: bold;
    margin: 3px;
}

.youtubecontent {
    margin-bottom: 20px;
}

A quick note about requirements:

Most hosts meet those requirements.

So there you have it. It's a quick and dirty way to get functional, always up-to-date Youtube streams in your WordPress posts and pages.

Possibly Related posts:

  1. New WordPress Plugin: Youtube Feeder
  2. Youtube Feeder WordPress Plugin
  3. My first WordPress Plugin: Project Honey Pot
  • http://www.billboardfamily.com Carl Martin

    OMG!!! This is exactly what I have been looking for. Finally!!! I do have some questions, if you do not mind. Is there a way to modify this to pull the main video full size, and the next videos as thumbnails, and have them all play int he same player when clicked? That would be a killer addition. Thanks!

  • http://andrewensley.com/ Andrew

    @ Carl Martin
    I'm glad this post was helpful. I've been thinking of a lot of ideas to expand the code. I'm pretty sure I'll eventually make it into a WordPress Plugin. If I do that, I'll definitely incorporate your idea along with a few others.

  • http://www.billboardfamily.com Carl Martin

    @ Andrew
    Thanks for getting back with me. I hope to see that plugin soon, you will be doing the WordPress community a huge solid. Thanks!

    http://www.billboardfamily.com is my site where Iam using your code.

  • http://www.billboardfamily.com Carl Martin

    Is there a way to pull the creation date of the main (or first) video to display it on a page with the video? I am trying to do just that on this page (note: the date is just today's date right now...I would like it to automatically update as a new video becomes the newest video on the page....as I will post a video every day).

    http://billboardfamily.com/videos/

    Also, have you had any luck turning this into a plugin like the one I emailed you about?

    Thanks!

  • http://andrewensley.com/ Andrew

    @ Carl Martin
    The published date is stored in:

    $vid['published']['$t']

    in that foreach loop. You can format it with:

    date('n/d/y g:ia', strtotime($vid['published']['$t']));

    Check out the doc page for PHP date() for more info on available formats. I'm still working on a rudimentary plugin. No ETA at this point.

  • http://www.billboardfamily.com Carl Martin

    Thanks. I just tried to add that code, but it really made wordpress mad....getting the dreaded fatal error. I am not very good with php/wordpress functions yet. Can you give me some more specific instructions, please, if you have time? Thanks!

  • http://andrewensley.com/ Andrew

    Sure, for example, you could replace lines 13-30 of my code with:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    foreach($data['feed']['entry'] as $vid)
    {
        $url = $vid['media$group']['media$content'][0]['url'];
        $title = $vid['title']['$t'];
        $date = date('n/d/y g:ia', strtotime($vid['published']['$t']));
        $ycontent = $vid['content']['$t'];
        $content.= '<object width="'.$width.'" height="'.$height.'">'.
            '<param name="movie" value="'.$url.'"></param>'.
            '<param name="allowFullScreen" value="true"></param>'.
            '<param name="allowscriptaccess" value="always"></param>'.
            '<embed src="'.$url.'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="'.$width.'" height="'.$height.'"></embed></object>'.
            '<div class="youtubetitle">'.$date.' - '.$title.'</div>'.
            '<div class="youtubecontent">'.$ycontent.'</div>'."\n";
        $counter++;
        if($counter == $limit)
        {
            break;
        }
    }

    Also, it appears my plugin idea is far from original. I just did a quick search on the wordpress.org plugins page and found these two that might work for you:

    TubePress

    TubeMatic

  • http://www.billboardfamily.com Carl Martin

    @ Carl Martin

    Thanks. As for those 2 other plugins...they both create really difficult code to change with css...and your code has one thing that NO OTHER wordpress plugin does....the ability to just enter a username and pull the videos that way. Those 2 other plugins you either need the individual code of each video (sucks if you add a video every day and want the newest video only). I spent a week trying every plugin out there, and your code is the only one I found that got the videos the way I needed.

  • http://www.billboardfamily.com Carl Martin

    Also, one last thing...sorry if I am bothering you. How can I call that date to display it somewhere other than with the video metadata? I actually need it where the date is shown on my page:
    http://billboardfamily.com/videos/

  • http://andrewensley.com/ Andrew

    You could put this function in your functions.php file:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    function youtube_published_date($user = null)
    {
        // Defaults:
        if(!isset($user))
        {
            $user = 'flamadiddle86';
        }
        $data = @json_decode(file_get_contents('http://gdata.youtube.com/feeds/api/users/'.$user.'/uploads?alt=json'), TRUE);
        $date = $data['feed']['entry'][0]['published']['$t'];
        echo date('n/d/y g:ia', strtotime($date));
    }

    And then call the function wherever you need the date output:

    1
    youtube_published_date('flamadiddle86');
  • http://www.billboardfamily.com Carl Martin

    Wow, you are awesome. Thanks again. I just tried that Tubematic plugin...and, unfortunately, it does not seem to work at all. I think your plugin is much needed! Ciao

  • http://www.billboardfamily.com Carl Martin

    I just put in that new function, and it is not pulling the right date for some reason. The date of the newest video does not match the date displayed. Check it out: http://billboardfamily.com/videos/

  • http://andrewensley.com/ Andrew

    Did you change the username in the function call? I notice the date matches my feed and not yours :-p

  • http://www.billboardfamily.com Carl Martin

    oops. thanks.

  • http://andrewensley.com/ Andrew

    @ Carl Martin

    No Problem.

  • http://www.billboardfamily.com Carl Martin

    @ Andrew

    I changed the username to DiscoveryNetworks , which is the channel all the videos are from on that page (for testing purposes), and the date is still not correct ... hmmmmmm

  • http://andrewensley.com/ Andrew

    When I call the function I wrote above like so:

    youtube_published_date('DiscoveryNetworks');

    I get this:

    9/01/10 10:04am

    Maybe you have a caching plugin that's saving the old value?

  • http://www.billboardfamily.com Carl Martin

    I am using W3 Super Cahce, which I just disabled.....but I am still getting the incorrect date.

  • http://www.billboardfamily.com Carl Martin

    Nevermind .. i tis working now. Thanks!

  • http://www.brandshank.com Liam

    This is excellent, very useful - been having issues with some youtube feed plugins but this cuts all that out. Thanks!

  • http://www.bestwirelessmouse.co.uk Best Wireless Mouse

    Great shortcode Andrew... lightweight and handy, any idea whether it can be used to manipulate the styling of the end result? In a similar way to the Youtube with Style plugin? We are just putting the finishing touches to our Youtube channel, and this will feed in perfectly to the site from there. Thanks, BWM HQ!

  • Jackson

    Many thanks for this.

  • http://twitter.com/XTgamer XTgamer

    Fullscreen doesnt work with this. YouTube says in the line 19 you need a ?fs=1 after your URL to have fullscreen enabled.

    ''.

    How do you add an ?fs=1? I always get an error if I add it after the .$url. Is there another way to add it in the code somewhere?

    Here is the YouTube link to the code you need. Look for fs!
    http://code.google.com/intl/de-DE/apis/youtube/player_parameters.html

    • http://andrewensley.com/ Andrew

      The "?fs=1" isn't working because there's already a ? in the embed URL.  Without getting too technical, URLs (in this form anyway) are only allowed to have one.  Try adding "&fs=1" after the $url, replacing the '?' with '&'.

      Also, I have written a plugin based on this code called Youtube Feeder that might help you.  It has a playlist style (that looks a little nicer), caching, and other options you can set in the WordPress admin panel.

      • http://twitter.com/XTgamer XTgamer

        Nope, "&" doesnt change anything. Thanks for the hint. I'm gonna stick to the code because your plugin seems not so handy to configure for my purpose (titles after the video, description doesnt work (it's ticked), playlist is a nice idea but only if you wanna display 3 videos). Can you tell me how to add an date of the video into the code above? Many thanks.

        • http://twitter.com/XTgamer XTgamer

          And another one: Can I only show videos of a specific playlist where I put uploaded videos that should be displayed? That would be more important than the date.

  • http://twitter.com/XTgamer XTgamer

    Okay now I experience no error with             ''. but still no fullscreen button in my embed player at http://www.xtgamer.de/videos

    • http://andrewensley.com/ Andrew

      You're a little too quick for me :-) .  See my reply below.

  • Iomethod

    WOW, this is exactly what i was looking for.  Is there a way to display specific videos from a user by using the ID that comes with the embed code? Also, how do i get the title and description to show to the right of the video instead of under? i know the css controls that but i'm having a tough time.

  • Pingback: Link: Embed YouTube Channel’s Feed in WordPress (Shortcode) - Professional Web Developer, Designer - Wordpress Theme Design - Mobile Website Design - Ottawa, Canada - Wilder Tweedale - Web Designer - Blog

  • Alison

    Is there a way for the thumbnail videos that are usually on the right handside to be displayed at the bottom?

    Thank you!

    • http://andrewensley.com/ Andrew

      Hi Alison, I'm not quite sure what you're referring to.  Perhaps you are talking about the "playlist" style of my Youtube Feeder plugin?

  • http://twitter.com/marmalade marmalade

    Amazing. Thank you so much, this saved me hours of work tonight. Very much appreciated!

  • Pingback: embedding you tube videos wordpress - DesignersTalk

  • Blob

    too bad it doesn't work by category or keywords

    • http://andrewensley.com/ Andrew

      This bit of code was never intended to embed anything but a user's upload playlist.  Feel free to check out my WordPress Plugin based on this code.  It offers a much simpler install method, more options, and embedding other user and global playlists is a planned feature for version 2.0.

store
forum