Wordpress Shortcode Handlers (YouTube Plugin)

Whilst there are many YouTube Wordpress plugins available, when I needed a YouTube plugin on another site I needed to add extra code surrounding the standard embedding iframe code, in order to have the YouTube video resize with the browser. I didn’t know how to do shortcodes at the time, so when I learnt how to use it, I thought this guide may be handy to a few people.

The small YouTube plugin I produced, simply allows the user to simply add a YouTube video to their Wordpress post, by typing [yt id=“video ID”].

Installation

Here I tell you how to install this YouTube plugin. Firstly I went into my themes functions.php file, and at the bottom within the php brackets I entered:

add_shortcode('youtube', 'insertYouTube');
add_shortcode('yt', 'insertYouTube');

// Insert YouTube function
function insertYouTube( $atts, $content = null ) {

	extract(shortcode_atts(array ('id' => 'attribute id'), $atts ) );

return '<div class="video-container"><iframe width="480" height="390" src="http://www.youtube.com/embed/' . $id . '" frameborder="0" allowfullscreen></iframe></div>';
}

Then when I wanted to add a video in one of my posts, I would simply enter:

[yt id="youtube ID inserted here"]

or perhaps…

[youtube id="youtube ID inserted here"]

The ID is the unique letter/combination at the end of the YouTube URL. For example, one of my videos is http://www.youtube.com/watch?v=vvXYt8Cy6O0. The ID here is therefore vvXYt8Cy6O0.

How it Works

If you’re not too fussed with how it works, and how to create your own shortcode handlers, then you can stop reading now; if so keep on reading.

add_shortcode('youtube', 'insertYouTube');
add_shortcode('yt', 'insertYouTube');

This simply registers a “shortcode handler”, which in this case is the function insertYoutube, so that within your posts you can use the function’s ability by calling either [yt id="#"] or [youtube id="#"].

extract(shortcode_atts(array ('id' => 'attribute id'), $atts ) );

That segment of code simply rips out data you passed through in the post being id="#" and allows the youtube ID passed in to be used within the function.

return '<div class="video-container"><iframe width="480" height="390" src="http://www.youtube.com/embed/' . $id . '" frameborder="0" allowfullscreen></iframe></div>';

Here, the embed video is displayed. The $id is what was passed through from the post. The <div class="video-container"> was required to resize the YouTube video with the browser window size, otherwise it is not needed (unless you want to style the outside the video).

Have a look here at Web Designer Wall for the code required to make your videos elastic.