Displaying YouTube Thumbails in Your WordPress Posts

Since I already wrote the snippet of code to get the thumbnails from the embedded Vimeo video, I thought I might as well do the same for YouTube. It will search through your posts’ content for YouTube embed code and will generate a thumbnail for you. It’s not fancy but it gets the job done.

So there are 2 types of YouTube URL’s that I’ve come across and here’s the code to deal with each (note: my code adds a link to the post)

http://www.youtube.com/watch?v=VIDEOIDYouTube URL’s added directly to a WordPress post/page.

<?php
$link = get_permalink();
$sourcestring = get_the_content(); 
preg_match('/http\:\/\/www\.youtube\.com\/watch\?v=([\w-]{11})/',$sourcestring,$matches); 
$youtube_video_id = $matches[1];
if (count($matches) != 0) {
echo '<a href='.$link.'><img src="http://img.youtube.com/vi/'.$youtube_video_id.'/0.jpg"></a>'; 
}
?>

http://www.youtube.com/v/VIDEOIDYouTube URL’s used in the embed code

<?php
$link = get_permalink();
$sourcestring = get_the_content();
preg_match('~(?<=www\.youtube\.com/v/)[^&?]*~', $sourcestring, $matches);
if (count($matches) != 0) {
	$youtube_video_id = $matches[0];
	echo '<a href=' . $link . '><img style="width:440px;" src="http://img.youtube.com/vi/' . $youtube_video_id . '/0.jpg"></a>';
}
?>

Just add this anywhere inside the loop

Again, nothing fancy but it gets the job done!

Tags: , , ,

Leave a Reply