Story of writing a custom VueJS audio button for WordPress Gutenberg
It may not seem like it, but this audio button (screenshot below) took quite a bit of time to get working:
The button is a custom Gutenberg editor “block” I wrote. That means we can feature any of the thousands of audio recordings we have on Bitesize by specifying it ID when writing a post (or lesson).
Gutenberg is the default editor for WordPress. You build your page up through “blocks”. A block can be a heading, a paragraph, or something a little more complex like an image with a caption.
Gutenberg allows developers to create custom blocks. So between your paragraphs you can have your own block (let’s say you’re a property listing site, then you might invest into developing a block that features a specific property).
The editing view
Let’s say I’m writing a blog post. I write a paragraph, but then I insert our custom audio button block. It asks me for a “Sound ID” (which I have to get manually from another page). That’s all that’s being stored in WordPress: the Sound ID I want the audio button to play when someone views the page.
The mechanism I used for this custom block was the Advanced Custom Fields (ACF) plugin for WordPress, which allows you to create custom Gutenberg blocks.
That’s the storage of an ID field, but how do you get it to load the audio info and show a play button?
The VueJS audio button
I had already separately developed the audio button for Bitesize Irish quizzes. It was a real treat to develop it in Vue (I love the simplicity of Vue).
With the ACF custom block (see above), you get to define what the block outputs to the browser. So each audio button is its own little instance of VueJS. The ACF block outputs a custom element <bitesize-audio-button> and creates a Vue instance on that element.
The Bitesize audio button written in VueJS is responsible for:
- Defining the HTML template of the audio button itself
- Making a request to the sounds API, given the sound ID, to get the Irish language, English translation, and phonetic pronunciation of this phrase
- Making an “new Audio()” instance, loading in the MP3
- Playing/stopping the audio for the user
I had to also edit the theme, so that the audio button’s script file and CSS file are loaded once per page.
Back to the learner
This is all in the goal of helping people learn and speak the Irish language. With this audio button, we’ll be able to develop rich lessons right in WordPress, with the ultimate goal of having a full program covering lessons and a community.