YouTube Snippets WordPress Plugin

I made a little shortcode plugin for making it fairly easy to embed YouTube video snippets. The plugin supports both a start and end time or either a start or end time. It also now allows you to embed multiple videos on a single page.

The plugin works like below. Times are in seconds.
[yt_video id=”xxxxxxxxx” start=”101″ end=”117″]

It’s a slight evolution of the code I found at Amit’s site after a quick Google search. This version obviously ties into WordPress but it also supports multiple videos and stops the video from displaying related videos.

The uses for this are pretty wide open. Seems like film studies would have lots of reason to chop up scenes and display them with additional written context.1 Lots of classes would have reasons to chop up YouTube videos to show exactly what they want.

Minor Figuring Out of Stuff

The only real thing to figure out was how to deal with multiple videos on one page. The original code looked for a single ID on the page. I needed to both generate and find as many unique ideas as people might need.

A bit of Google and I found a Stackoverflow bit to create a random string.

substr(md5(microtime()),0,20);

Then the ID of each div created by the shortcode becomes id=”youtube-player-‘.randId().’ with randId being a 20 character random string. It’s possible it’ll be repeated but pretty unlikely.

Now the javascript needs to find the various video divs and get the IDs to make the script work.

unction getVids (){
  vids = document.getElementsByClassName('yt-video');
  console.log(vids);
  for (i = 0; i < vids.length; i++){
  onYouTubeIframeAPIReadyClass(vids[i]);
  }
}

That gathers the videos up and the following function applies it to each video.

function onYouTubeIframeAPIReadyClass(theVideo) {
    var theId = theVideo.id; //gets ID of div
    var player = new YT.Player(theId, {
        height: theVideo.dataset.height,
        width: theVideo.dataset.width,
        playerVars: {rel: 0},//turn off similar videos 
        events: {
            'onReady': function(e) {
                e.target.cueVideoById({
                    videoId: theVideo.dataset.video,
                    startSeconds: theVideo.dataset.startseconds,
                    endSeconds: theVideo.dataset.endseconds
                });
            }
        }
    });
}

1 Maybe a loop parameter would be useful . . .