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.
- 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:
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:
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.
Latest posts by Rafał Gicgier (see all)
- OptiPic.io – How and why to optimize the image on the site? - 8 April 2019
- Guest post at WP doin! - 26 March 2019
- A Gutenberg WordPress 5.0 plugin review. Is it worth it? - 8 December 2018