Embedding videos from Youtube into a website is a rather painless procedure. Each video is provided with sharing options that include a bit of html code that will get the job done, and with WordPress it's even easier. All you need is the video URL and the oEmbed protocol included in WordPress will take care of the rest of the embedding for you. These solutions put the video directly into your content, which is fine if you are adding only one or two, but when we're dealing with many videos to be collected on one page this is far from ideal. In these cases I usually opt to put together a solution using the Fancybox modal window script and a video thumbnail image link.

In this scenario, the video page displays a collection of thumbnail images, or "covers", that when clicked on load the video player in a modal window. Luckily, Youtube automatically generates thumbnail cover images for each video uploaded, which we can access with a specific URL structure and video ID. To make this task as easy as possible, I use a custom PHP function written by  Samer Ata that takes the video URL and uses it to create the URL to the thumbnail image, taking care of all the dirty work behind the scenes.

The Function

Let's take a look at the custom function itself:

function youtube_thumbnail_url($url)
{
if(!filter_var($url, FILTER_VALIDATE_URL)){
return false;
}
$domain=parse_url($url,PHP_URL_HOST);
if($domain=='www.youtube.com' OR $domain=='youtube.com')
{
if($querystring=parse_url($url,PHP_URL_QUERY))
{
parse_str($querystring);
if(!empty($v)) return "http://img.youtube.com/vi/$v/1.jpg";
else return false;
}
else return false;
}
elseif($domain == 'youtu.be')
{
$v= str_replace('/','', parse_url($url, PHP_URL_PATH));
return (empty($v)) ? false : "http://img.youtube.com/vi/$v/1.jpg" ;
}
else
return false;
}

So first the function checks that we have fed it a valid URL. Then it determines which type of Youtube URL it is (youtube.com or youtu.be) and grabs the video ID accordingly. Finally it creates the thumbnail image URL with the extracted video ID.

Usage

Here's what a usage example of the function looks like:

if($img=youtube_thumb_url($url))
$img=htmlspecialchars($img);
echo '<img src="'. $img .'" alt="" />';
else
echo '<img src="noimage.png" alt="" />';

 

May this function serve you well as it has me... enjoy!