I’m currently developing a WordPress site which will have some YouTube videos to embed. The site owner is not interested in HTML, so I decided to write a few lines of Javascript to automate the embedding on the fly.
After embedding the video, we also want to track which videos will be watched on the site. This proved slightly more convoluted, as the YouTube embedded videos only offer very limited events functionality.
The script below requires that Google Analytics’ ga.js, SWFObject and jQuery are included before.
The WordPress post editor has a Media bar, where you can enter a video by URL, which inserts a link to the YouTube video in the post.
On the frontend, after the DOM has loaded, the script searches the page for YouTube video URLs, and expands each one into an embedded video. Then, each video’s “onStateChange” is replaced with a custom function, which fires off an event to Google Analytics. The event value name is the content of the link to the YouTube video.
Currently the script only tracks when a video has finished playing throughout; as I update it to track more events (like the start of a video playing, for example), I will update this code & post. The script works for multiple videos on the same page.
Remember to update the tracking with your own Google UA code, and to set the video’s width and height properties.
With thanks to: YouTube JS API docs & YouTube API Dev Forum