YouTube and Vimeo are the most popular video-sharing websites from across the internet. They truly changed the world by entertaining, informing and inspiring people through video.
Their scope is more than just showcasing videos. They are platforms for debates, stages for future music stars and veritable virtual classrooms.
Although the platforms are invaded by billions of people each month, videos can be used by other websites as well, through the embed codes. In just a few clicks, you can get an embed code out of YouTube or Vimeo and paste it in your website`s files or on a WordPress blog post.
Today I want to present you a different way of how to embed such codes into a website. To be more specific, I want to show you how to generate an embed code out of an URL. The technique works for YouTube and Vimeo URLs, but it can be easily expanded to support other video-sharing platforms as well. I`ll try a PHP approach, which can be implemented into any PHP based website, including blogging platforms like WordPress.
Every YouTube or Vimeo URL contains an unique key or ID. We`ll grab this key and use it to generate our own embed code.
Custom YouTube Embed Code
//store the URL into a variable $url = 'http://www.youtube.com/watch?v=x6qe_kVaBpg'; //extract the ID preg_match( '/[\?\&]v=([^\?\&]+)/', $url, $matches ); //the ID of the YouTube URL: x6qe_kVaBpg $id = $matches; //set a custom width and height $width = '640'; $height = '360'; //echo the embed code. You can even wrap it in a class echo '<div class="youtube-article"><iframe class="dt-youtube" width="' .$width. '" height="'.$height.'" src="//www.youtube.com/embed/'.$id.'" frameborder="0" allowfullscreen></iframe></div>';
Custom Vimeo Embed Code
//store the URL into a variable $url = 'http://vimeo.com/71673549'; //extract the ID preg_match( '///(www.)?vimeo.com/(d+)($|/)/', $url, $matches ); //the ID of the Vimeo URL: 71673549 $id = $matches; //set a custom width and height $width = '640'; $height = '360'; //echo the embed code and wrap it in a class echo '<div class="vimeo-article"><iframe src="http://player.vimeo.com/video/'.$id.'?title=0&byline=0&portrait=0&badge=0&color=ffffff" width="'.$width.'" height="'.$height.'" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe></div>';
If you`re wondering where these functions can be used at, I`ve been successfully tested them into a WordPress theme. The deal was to extend a video blog post format by adding it a custom field for YouTube and Vimeo URL. The user pastes an URL which is converted into embed code and implemented into the blog system. Pretty neat!
Let me know your thoughts about this tutorial and feel free to leave your feedback into the comments section!