What started as a potentially complicated plan to enhance the "Insert Media" area ended up in a really simple add_filter() solution.
I recently helped my brother-in-law with his web site. He is a music teacher and uses the site to distribute documents, audio files and lessons to his students.
Double Insert Media
He has uploaded a number of mp3 files and they are displayed as a playable track, using the “Embed Media Player” attachment option in the “Insert Media” screen. This worked well for most students but some requested a download link so that they could download the files when they had a good internet connection, and listen to them when an internet connection was not available. I directed him to insert the mp3 file a second time, choosing the “Link to Media File” option this time. He edited all his posts to add this.
Obviously this is tedious and easy to forget so I started looking into ways to automate this.
Extend Insert Media Dropdown
My first approach was to look to adding a new option to the “Attachment Display Settings” dropdown. I searched the WordPress source for the “Embed Media Player” text and found it in the wp-includes/media-template.php file. I did not see any apply_filters() or add_action() calls that would allow me to add to the dropdown. So, this looked like a dead end.
Extend the ‘audio’ Shortcode
Next I looked at the ‘audio’ shortcode function. This is defined in wp-includes/media.php in wp_audio_shortcode(). The last line in the function is an apply_filters() call. I wrote a tiny function to log the data sent to the filter:
The following info was logged:
The solution would be to simply append the mp3 url to the $html parameter.
While my brother-in-law has only updated mp3 files, I decided to make my code more flexible and handle other audio types.
In the logged data I saw that the $atts array had elements for ogg, wma, m4a and wav audio types. I wrote the code to go through the five audio types and use the url of the first one found as the target of the download link. I doubt that it is possible for more than one audio type to be populated at once but I decided to play it safe.
The download link is a button element as the default styling looks like a button (surprise, surprise!).
The file above can be used to append a download button under the audio player.
As a way to help me learn about GitHub and deploying plugins from GitHub, I have created a repository for the code. I now need to learn git command line.
The code is definitely a “minimal viable product” as is but I may enhance it to allow the appended html code be changed (another apply_filter() call!). I will also look to see if additional audio types can be supported by the ‘audio’ shortcode and see if I can dynamically support these.