FlannelBeard
FlannelBeard

Reputation: 65

Youtube Get Thumbnail

Trying to do a few things in my new Wordpress Youtube niche theme. I have a tab in my theme for the user to input the Youtube watch?v=xxxxxxxxxxx id. When they enter the xxxxxxxxxxx url it outputs the video, showing 16 posts per tab via the 'loop' query.

Working example here

I have looked into this Google developer console api thing... and it is complete gibberish to me. I'm using custom post types for the 4 categories youll see on my site. only "Comedy" is populated right now.

NEW EDIT: THIS WORKS. Thank you all who have helped me figure this out!

<?php
  $new_query = new WP_Query();
  $new_query->query( array('post_type' => array( 'comedy' ), 'orderby' => 'title', 'order' => 'asc','showposts' => 16, 'paged'=>$paged ));

  while ($new_query->have_posts()) : $new_query->the_post();

  $url = get_post_meta ($post->ID, 'comedy_url', $single = true);

  include(TEMPLATEPATH . '/library/variables.php');

  $code = 'http://www.youtube.com/watch?v=' . $url;
  $json = file_get_contents('http://www.youtube.com/oembed?url='.urlencode($code));
  $video = json_decode($json);
?>

<img src="<?php echo $video->thumbnail_url ?>" />

Upon pulling the thumbnail some of you may notice BLACK BORDERS on the top and bottom of your thumbnail. To fix this use the code below:

<a href="<? if($code) {?><?php echo $code; ?><? } ?>">
  <div class="yt-thumbnail" style="background:url('<?php echo $video->thumbnail_url ?>') center no-repeat;"></div>
</a>

// in your css file 
.yt-thumbnail{
    height: 164px;
    width: 300px;
    background-size: 300px 220px;
}

Upvotes: 1

Views: 1305

Answers (1)

Gergo Erdosi
Gergo Erdosi

Reputation: 42073

You can use the oEmbed API to get thumbnail, uploader name and title. All you need is to encode the URL of the video, for example:

http://www.youtube.com/oembed?url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D9FOWI6Zftpg

This will return a JSON response:

{
  "provider_name":"YouTube",
  "version":"1.0",
  "author_url":"http:\/\/www.youtube.com\/user\/NScherzingerVEVO",
  "type":"video",
  "author_name":"NScherzingerVEVO",
  "thumbnail_url":"http:\/\/i1.ytimg.com\/vi\/9FOWI6Zftpg\/hqdefault.jpg",
  "provider_url":"http:\/\/www.youtube.com\/",
  "title":"Nicole Scherzinger - Your Love",
  "height":270,
  "width":480,
  "thumbnail_height":360,
  "html":"\u003ciframe width=\"480\" height=\"270\" src=\"http:\/\/www.youtube.com\/embed\/9FOWI6Zftpg?feature=oembed\" frameborder=\"0\" allowfullscreen\u003e\u003c\/iframe\u003e",
  "thumbnail_width":480
}

Getting the view count is a bit more difficult, see the answers here for details.

Edit:

Here is an example how to get the thumbnail in PHP:

<?php
  $url = 'http://www.youtube.com/watch?v=9FOWI6Zftpg';
  $json = file_get_contents('http://www.youtube.com/oembed?url='.urlencode($url));
  $video = json_decode($json);
?>
<img src="<?php echo $video->thumbnail_url ?>" />

Upvotes: 1

Related Questions