Posts Tagged videos workaround

Display YouTube Thumbnail with wordpress custom field

Note:

Before using the code bellow, I strongly recommend you to take a look on my YouTubeNails plugin, wich is a evolution of the function bellow and you can easily configure as a widget.

Why saving a video thumbnail for a video hosted on YouTube, when you can use the YouTube API plus WordPress Custom Fields to display the thumb, without working around crops, size and other stuff like this.

All you need:

  1. Create a custom field called(slug) “link_video”, which contains the standard “share” url from YouTube, something like this http://www.youtube.com/watch?v=kBN9_deleBg”;
  2. Use the code bellow, to retrieve data, inside a WordPress Loop;
<?
if (have_posts()) : 				
  global $post;
  $strquery = "category_name=videos";
  $myposts = get_posts($strquery);
  if($myposts):
	foreach($myposts as $post) :
             setup_postdata($post);
            // get meta from the custom field, using its slug
            $videolnk = get_post_meta($post->ID, 'link_video', true);
            // pure php string replace
           // add the standard YouTube API call for video thumbnails
           $videolnk = str_replace('http://www.youtube.com/watch?v=','http://img.youtube.com/vi/',$videolnk);
           $videolnk .= "/2.jpg";
        endforeach;
  endif;
endif;
?>

Then you can call the code bellow on your page(inside the loop):

<a href="<?=get_permalink()?>">
<img src="<?=$videolnk?>" width="214" height="129" >
</a>

Go to the source, if you need further info about YouTube API.

Advertisements

, ,

9 Comments

%d bloggers like this: