Share

WordPress comes up with nice video and audio player plugin – MediaElement.js. Since it’s part of a core its default functionality is not perfect and actually it’s quite hard to customize. For instance it’s impossible to trigger custom event handlers, which make it not much usable.

Use cases

  • A site with video / audio views counter
  • A site with IE8 flash fallback
  • A site with mobile devices fallback

Certainly most of the time you will need custom handler to handle these.

In the following small tutorial I’ll give you couple of handy tips on how to create custom MediaElement handlers.

Deregistering the scripts

First, we need to remove the default mediaelement.js and related scripts. The hook named mediaelement is the default mediaelement library boundled with the core, wp-mediaelement is WordPress custom script, which triggers the mediaelement object on all .wp-video-shortcode and .wp-audio-shortcode elements. Next we’ll need to enqueue these two scripts, the first one will be the newset mediaelement.js library and the other one, will be our custom mediaelement.js handler, which gives the ability of adding extra functionlity.

The following hook:

Overwrites the default medaielement scripts and enqueues useful mediaelement.js media detection plugin. It also assigns custom JavaScript object, to be available from within the .js code. This is done thanks to the wp_localize_script method.

You can find all of the mediaelement.js plugins at: https://github.com/johndyer/mediaelement/tree/master/src/js

 Creating custom event handlers

Now, imagine we’d like to fire an event on a video being played. This would solve the video counter need. Let’s edit the contents of our wp-mediaelement script:

As you can see we have added couple of functions to the similar, WordPress made code:

The important part starts here: the EventListener function, runs the code from within the braces after the video has started playing (so it needs to be loaded and open to actually fire). The trigger_view is a custom JavaScript function, which communicates with the server:

Above I’m sending doing a server POST request, via jQuery.post() method. ‘some_url’ needs to be exchanged with a real URL, that would parse the request (connect to the database, check the ip for multiple views, handle the nonce) and return the info.

I’ll cover the server side solution in the next tutorial.

 

 

The following two tabs change content below.
Working as senior WordPress developer with XFive I have been involved in more than 500 projects. I'm posting tips and tutorials around this blog as well as gathering clients.