Tracking YouTube with Google Analytics

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

Credit File

Make sure you know what’s on yours!

Get your statutory files from both these companies:

www.equifax.co.uk

www.experian.co.uk

It costs £2 at each company; you will need a credit card registered at your current address to order your report.

Backups

As I develop a website, whether it’s a full customer-management system in symfony or a basic theme in WordPress, I regularly save my work using subversion.

My code repositories, databases and uploaded web content are backed up every night, to a remote server provided by rsync.net.

Should the worst happen, I can restore a working web server in less than 1 hour, with minimal loss of data.

Almost as importantly as making sure you have a copy of your data on another server (or service), you should ensure that you are able to use those backups to recover from a catastrophe.

Ethical Web Development

It’s all about the good things, and trying to minimise the bad ones.

Delivering on time, keeping the channels of communication open until the project is complete.

By using open-source frameworks, I can spend more time customising your web application than re-inventing the wheel.