How To: Create Your Own Free WordPress Video Player Plugin & Shortcode
Let’s face it, when it comes to WordPress video players there are a lot of options.
You could publish your videos on YouTube and then embed them on your site, but you then give up the ability to customize the look and feel of the video player.
Alternatively, you could get a WordPress plugin… some of which have thousands of installations but most of them have features behind a “Pro” or “Premium” version.
Additionally, from my experience, a lot of the video players are often bloated and poorly written, so much so that after you uninstall the plugin, remnants of it remain in your database.
In this blog post, I’ll quickly go through some of the positives and negatives of using a third-party video player plugin. Then, you’ll learn that you can easily build your own WordPress video player plugin with a short code using free, open source software.
The WordPress Plugin Ecosystem
There’s a reason why WordPress powers over 63% of all content management system websites. One of the main reasons for it’s popularity is its vast ecosystem of plugins that allow users to extend existing or add new functionality to their website with just a few clicks. However, just a few clicks is all it takes to cause errors and add unnecessary bloat to WordPress, even after uninstalling a plugin.
Database bloat, or having unnecessary data in your database, can wreak havoc in regards to WordPress performance. This is because many plugins add data to your wp_options table and automatically load. Plugins that are poorly written sometimes don’t remove this data and it’s referred to as “orphan data.”
This is why I have plugins such as Meow App’s Database Cleaner. This plugin gives you incredible insight into your database, can automatically clean it, and much more.
My Problem with WordPress Video Player Plugins
When it comes to embedding a video on a page or within a post, you have a ton of options. As I mentioned in the introduction, you could use just insert the HTML from YouTube or Vimeo to embed your video.
If you wish to not use YouTube or Vimeo and have your videos hosted somewhere, there are options like Bunny.net who can store your video and provide you with an HTML player to embed.
Then you have dedicated WordPress plugins. While I can’t say that I’ve tried them all, I’ve tried plenty enough to say that the convenience that some of these plugins offer come at a steep cost.
By cost, I don’t just mean monetarily, though that’s a factor as many of them have “Premium” versions if you want to do something as much as change the color of the player.
Most of these video player plugins simply try to do too much besides just being a video player. The want to offer integrations with your email marketing service, your CRM, or have, in my opinion, those annoying popup videos.
I just wanted a video player that I could fully customize and for it to be easy to use from within WordPress, so I started my research.
Building Your Own WordPress Video Player Plugin
From the get go, I used my previous experience with video players and video hosting providers to know that I wanted to use the open-source video player Plyr.
From their GitHub repo, “Plyr is a simple, lightweight, accessible and customizable HTML5, YouTube and Vimeo media player that supports modern browsers.” Plyr has over 23.8k stars on GitHub and is actively maintained.
Besides being open-source, Plyr offers the ability to do one thing that many other video players, even the paid ones, and that’s the ability to display a “storyboard” or “preview thumbnails” which allows viewers to see a preview of the video by hovering over the timeline of the video.
That said, not all video hosting providers offer this feature. However, once upon a time, long, long ago, I stumbled upon Mux.
How To Use Mux To Host Your Videos
I’ll be transparent and say that if you go to their website it’s clear that their target demographic is geared more towards developers.
Mux Advantages
One of the primary advantages of using Mux is that it takes your original video, most likely in a MP4 of MKV file format, and transcodes it to a M3U8 file format.
M3U8 is a file format allows for adaptive bitrate streaming (ABS), also called adaptive HLS streaming, that was developed to effectively provide video at the highest possible quality possible based on the viewer’s internet speeds and networking conditions. ABS is able to achieve this by concurrently transmitting numerous streams of material at various bitrates. To give you a better idea of ABS, refer to the image below.
So, Mux doesn’t just store and host your original video, it optimizes it so that your visitors get the best possible quality without buffering.
Additionally, Mux creates storyboards or video previews, in several formats: as an image, as a VTT file, and as a JSON file. For Plyr, you’d use the the VTT file, which gives “instructions” to the player as to which image to show at a particular time. The image format can be PNG or you can use a new file format called WebP, which offers high quality images at a reduced file size.
Lastly, Mux creates a default video poster for your video. The default image for the poster is from the half-way point of the video. However, you can change the poster easily by adding a “time” query string parameter with the value set to the second you want your poster to be.
There are additional features, such as being able to generate short animated clips, etc. You can find more of Mux’s features on their website.
Mux’s Drawback
For me, there’s only one drawback and it could be a deal breaker to some. The drawback that many will first notice is that Mux doesn’t have a direct upload tool for you to upload your videos. So, you have to bring out your inner “techie” a bit, but I assure you it’s worth it.
Mux receives your videos by downloading them from a given URL and from their website you could then make a request to have them download and prepare your video for streaming. One thing to mention is that they refer to videos as “assets”.
So, you could temporarily upload your video to your web hosting provider, then create a new asset in Mux, and then delete it from your host.
Getting Started with Mux
Whether you’re using their web interface or you use their API, you’ll be making a HTTP Post call to https://api.mux.com/video/v1/assets with the following body:
{ "cors_origin": "*", "input": "https://yourdomain.com/wp-content/uploads/videos/video.mp4", "mp4_support": "standard", "playback_policy": "public" }
Here are a couple of important notes:
- cors_origin is important as an asterisk as if you want the to have a storyboard, you’ll need to allow Cross-Origin Resource Sharing. This is a browser security feature that allows (or disallows) resources on a web page to be requested from another domain. So, in this case, resources from your website will be able to call resources from Mux.
- mp4_support is optional, but recommended as “standard” as this will provide you with several different qualities of mp4 videos that you can post on other sites, share, etc. Without this variable, Mux will only create an M3U8 file.
Get To Know Mux’s API with Postman
If you don’t mind getting your hands dirty with some light programming, Mux maintains a collection of all their API requests using Postman.
With Postman, you can make API calls directly from the app. What’s especially helpful about Postman is it can generate the code you’d need in almost every programming language in the event you wanted to build something yourself or use a no-code tool such as n8n, Make.com, or an Azure Logic App.
Checkout the screenshots below for an example:
How to Use an Azure Function to Automate Your Uploads
This is the option I took. Running an Azure Function on the “Consumption Plan” is extremely inexpensive. However, in order for this function to be fully automatic it’s going to rely on an Azure Storage Account. You’ll also need the Azure Storage Explorer application so you can upload videos straight from your desktop.
Basically, we’ll create an Azure Function that runs automatically when a new video (a “blob”) is uploaded within a particular storage container.
Here’s an example of code written in C#, but keep in mind that Azure Functions can be written in JavaScript, Python, Java, or PowerShell.
You can view the full code and an alternative method which utilizes an Azure Logic App on GitHub.
public class DirectMuxVideoBlobTrigger { private const string BaseMuxApiUrl = "https://api.mux.com/video/v1/assets"; private const string BaseVideosContainerUrl = "https://myazurestorage.blob.core.windows.net/videos"; [FunctionName("DirectMuxVideoBlobTrigger")] public async Task Run([BlobTrigger("videos/{name}", Connection = "AzureWebJobsStorage")]Stream myBlob, string name, ILogger log) { var muxTokenId = Environment.GetEnvironmentVariable("MUX_TOKEN_ID"); var muxTokenSecret = Environment.GetEnvironmentVariable("MUX_TOKEN_SECRET"); var authenticationString = $"{muxTokenId}:{muxTokenSecret}"; var base64String = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(authenticationString)); var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, BaseMuxApiUrl); httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic", base64String); var muxVideo = new MuxAsset(); muxVideo.Input = $"{BaseVideosContainerUrl}/{name}"; using(var httpClient = new HttpClient()) { var request = await httpClient.SendAsync(httpRequestMessage); request.EnsureSuccessStatusCode(); } log.LogInformation($"Mux Video {name} sent to Mux API."); } } public class MuxAsset { [JsonPropertyName("cors_origin")] public string CorsOrigin { get; set; } = "*"; [JsonPropertyName("input")] public string Input { get; set; } [JsonPropertyName("mp4_support")] public string MP4Support { get; set; } = "standard"; [JsonPropertyName("playback_policy")] public string PlaybackPolicy { get; set; } = "public"; }
Once the video is uploaded to Mux, you can view the status and get the video’s Playback Id by navigating to their Dashboard and going to Video > Assets and then clicking on the video you just uploaded to see the status under “Recent Events”. The event you typically want to wait for is the labeled as “video.asset.static_renditions.ready”.
Using Mux Webhooks To Automatically Notify You
Instead of having to go to the dashboard every time you upload a video, you could automate the process by providing Mux with a Webhook URL.
You can generate a Webhook URL from many no-code platforms.
For me, I use a self-hosted version of n8n. However, you could do the same with IFTTT, Make.com, Pabbly Connect, Pipedream, an Azure Logic App, Zapier, and plenty of other no-code or low-code tools.
I’ll provide screenshots of my workflow below, but here are the general steps:
- The workflow is triggered by a webhook, which you set in you Mux Dashboard in Settings > Webhooks.
- It then checks the if the asset is ready by checking the “type” variable in the JSON body of the request. If “type” isn’t “video.asset.static_renditions.ready” the workflow stops, if it is it continues to the next step.
- In the third step, I extract the values I need from the request and build a new JSON object to make it easier to work with in the following steps.
- Now that I have the information I need, I want to send the relevant data to me. For me, I have it sent via Pushbullet so that I receive notifications on several devices and it makes it easy for me to copy and paste what I need. You could change this “communication” step to send you an email, send you a message on Discord, or a slew of other options depending on what workflow automation service you use.
- Next, I have it make a HTTP Request to an Azure Logic App which deletes the video from my storage account so that I don’t have to pay for storing it too long.
- Finally, the workflow ends.
n8n Workflow Example with Pushbullet and Azure Logic Apps
Using Other Video Hosting Provider
If you already have your videos hosted somewhere else and you’re happy with their service, you may not want to move to Mux and that’s not a problem!
However, you may need to alter this plugins code (and I’d be happy to assist) if your hosting provider doesn’t offer all the features that Mux offers. For example, they may not offer storyboards or the ability to dynamically select your video’s poster based on a “time” query parameter.
Making changes to accommodate your needs is very easy with this WordPress video plugin because the video player, Plyr, is extremely flexible.
Building Your Own WordPress Video Player Plugin
We’ve covered the video player, Plyr, and a video hosting provider, Mux, so now it’s the moment you’ve been waiting for: building your own WordPress Video Plugin.
Here’s the good news: I’ve already built a working plugin and the source code is open to the public on GitHub and you’re more than welcome to use it straight out of the box or fork it and create your own version.
Either way, if you have any questions, issues, or suggestions, please create an “Issue” on GitHub if you have an account. If you don’t have a GitHub account, you can leave a comment on this post.
Getting Started From GitHub
From GitHub, click the green “Code” button and then click “Download Zip.”
Once you’ve downloaded the Zip file, you’ll need to extract it’s contents as we need to modify a JavaScript file to supply it with your own Mux Environment variable. You could also make any other modifications as you see fit as the video plugin’s code is pretty straight forward.
Now, we just need to open the folder in your preferred code editor. Personally, I use Visual Studio Code, but JetBrains’ PhpStorm is a popular choice. For purposes of this post, the following steps will be for Visual Studio Code.
If you’re using Mux, all you need to do is edit the ajtd-plyer-hls.js file in public/js folder and find the muxData object and edit the “env_key” to be your environment key. Make any additional changes as you see fit, especially with the custom dimensions (they’re optional). Once you’re done, you’ll need to minify the JavaScript. In Visual Studio Code, press the Ctrl, Shift, P keys at the same time and a menu appears. Type Minify and press the Enter key.
Once you’ve made your changes to the project, go to the project folder and compress it so that it’s a Zip file.
Install Your WordPress Video Player Plugin & Shortcode
Simply go to your WordPress Dashboard, navigate to Plugins, and then click “Add New”.
You’ll now be at the familiar “New Plugin” page… at the top of the page click the “Upload Plugin” button and then click “Choose File” and select the Zip file you just created and click “Install Now”.
How To Use Your WordPress Video Player with a Shortcode
I’ve outlined how to use the plugin with a shortcode on the project’s README.md file, but I’ll quickly go over it here. Personally, rather than having to remember the shortcode all the time, I find it easier to use a plugin called Shortcoder.
In Shortcoder, provided that you keep the same variables, you can paste in the following:
ajtd_plyr playbackid="%%playbackId%%" videoid="%%videoId:playbackId%%" videotitle="%%videoTitle%%" previewtime="%%previewTime%%" m3u8="%%m3u8:true%%" mp4high="%%mp4high:true%%" mp4medium="%%mp4medium:true%%" mp4low="%%mp4low:true%%" topic="%%topic%%" product="%%product%%" isreview="%%isreview:false%%" softwareused="%%softwareused%%"
Now, when you’re editing a page you can simply add a new Shortcoder block, select the video player shortcode and fill in the prompts like so:
Conclusion
I don’t know about you, but I’m pretty excited about having a free, open-source-based WordPress Video Player Plugin with Mux Data integration so I can see how well my videos are doing.
I’m also pretty stoked to be able to provide the community with a relatively straightforward plugin that anyone can use as-is or make adjustments to suite their needs.
Best of all, I think this ended up also being a great introduction into creating a WordPress plugin and shortcode in general.
Oh, and how could this article end without an example of how the media player looks? Check it out!
FAQs
What is an M3U8 file?
M3U8 is a file format allows for adaptive bitrate streaming (ABS), also called adaptive HLS streaming, that was developed to effectively provide video at the highest possible quality possible based on the viewer’s internet speeds and networking conditions. ABS is able to achieve this by concurrently transmitting numerous streams of material at various bitrates. To give you a better idea of ABS, refer to the image below.
What does video transcoding mean?
Video transcoding is the process of decoding (or decompressing) one format, such as a MP4, and compressing it into another, such as a M3U8. In a nutshell, it refers to making numerous versions of the same video file. Transcoding assists creators in satisfying the expectations of their audiences by increasing the number of available devices on which viewers can view a video. It also enables them to create videos that are adapted to the user’s internet speed.
What Is A Video API?
An application programming interface (API) for video enables you to create, store, and deliver video. Many video APIs also allow you to get statistics on the videos and livestreams you show visitors. The advantage of a video API is that it is entirely adaptable; you can implement the API for whatever use case you choose.