WordPress Audio: Add a Download Button to mediaelement.js
So I got a call this morning asking how to download an audio file that WordPress was presenting with medialement.js. As you might have noticed, since WordPress started providing an audio player there hasn’t been an easy way to allow audio files to be downloaded as well as played. This has bothered me for a while, but this morning’s call gave me the incentive to look into it further.
My first thought was to use a custom field to store the audio file URL. Then I could display both a player and a download button based on the same URL. However, the site I was working on had years worth of audio, and I didn’t want to go through post by post and move the audio file URL out of the post editor and into a custom field. My next thought was to modify how WordPress loaded the media player and hopefully filter the output to add a download link. While this may be possible, I ended up deciding against digging into the filters in WordPress core and just used a few lines of jQuery. Here’s what did it:
// Add download links to default audio player. $( document ).ready(function() { $('audio').each(function( index ) { var source = $(this).find('source').attr('src'); if ( source != '' ) { $(this).after('<a href="' + source + '" class="audio-download" download>Download</a>'); } }); });
Keep in mind you’ll need to load jQuery in order for this to run.
I just added a few lines of CSS to style the new download buttons:
a.audio-download { margin-top: 1em; background: #eee; padding: 0.5em 1.5em; border-radius: 5px; display: inline-block; } a.audio-download:hover { background: #ddd; }
…and that’s it!