As an alternative to cutting and pasting the bloated Youtube code into your wordpress blog to insert a video, you have the simple option of creating a shortcode function. The advantages of shortcode for Youtube videos could be argued since the shortcode itself may prove more challenging than simply copying and pasting code provided on the Youtube website. However, the same priinciples in the below code can be applied to many other custom players. We’ll be providing some shortcode examples for some of the more popular MP3/Video players in a scheduled post. This code comes from my friend Christian.
With the following code, you will be able to embed a Youtube video into your post via the simple shortcode [yt video=”lFZ0z5Fm-Ng” /], where lFZ0z5Fm-Ng is the video ID attached to the video URL.
First, paste the following code into your theme’s functions.php file.
function embed_yt($atts, $content = null) {
extract(shortcode_atts(array(
'video' => '',
'width' => '475',
'height' => '292'
), $atts));
return '<div class="yt_video"><p><center><object type="application/x-shockwave-flash" style="width:'.$width.'px; height:'.$height.'px;" data="http://www.youtube.com/v/'.$video.'&hl=en_US&fs=1&"><param name="movie" value="http://www.youtube.com/v/'.$video.'&hl=en_US&fs=1&" /></object></center></p></div>';
}
add_shortcode('yt', 'embed_yt');
How to use the shortcode
When you arrive at a page on Youtube containing the video you want, you’ll notice the URL in the address bar looks something like this: http://www.youtube.com/watch?v=lFZ0z5Fm-Ng. It’s the video ID that you want to copy for inclusion into your shortcode.
http://www.youtube.com/watch?v=lFZ0z5Fm-Ng
To insert a video into your post, use the following shortcode:
[yt video=”lFZ0z5Fm-Ng” /]
By default, the video will size to 475 by 292 pixels in height. To change this, you can include those ‘variables’ in your shortcode as follows:
[yt video=”lFZ0z5Fm-Ng” width=”560″ height=”340″ /]
If you’re brave, and you want to add some style to the video, you can alter the code returned by the function. We’ll add some examples of additional players over coming weeks.
I’m using shortcode to output the Youtube video below.
|
|
If you liked this article, you may also like:


[...] (we’ve previously looked at how to render a YouTube video in your post with shortcode – check it out here). I’ll also provide some additional code for those that use [...]