Extending the Audio Shortcode

At the moment, the audio shortcode only allows four attributes, src, loop, autoplay and preload. When you upload an audio file however, it comes with pretty useful meta data such as the album art, artist, year and so on which would be great if it could be displayed as well. I’ve been looking for a way to extend the audio shortcode so that the meta data can be included in the shortcode as well.

So far I have stumbled across shortcode_atts_{$shortcode} which can be used to filter existing shortcodes, but apparently one can only filter existing attributes, not add new ones. I’m not looking to create a new shortcode btw, but add to or extend the existing one, so a user doesn’t have to use a new shortcode to get this effect. Is there anyway one can achieve this? I’m grateful for any pointers.

2 Answers
2

I would use the filter wp_audio_shortcode:

/**
 * Filter the audio shortcode output.
 *
 * @since 3.6.0
 *
 * @param string $html    Audio shortcode HTML output.
 * @param array  $atts    Array of audio shortcode attributes.
 * @param string $audio   Audio file.
 * @param int    $post_id Post ID.
 * @param string $library Media library used for the audio shortcode.
 */
return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id, $library );

It seems that $audio is not a string as stated but an object of type WP_Post, so you could use $audio->ID to get the meta values.

function wpse_163324_audio_filter( $html, $atts, $audio, $post_id, $library ) {
    // Use something like
    // $meta_values = get_post_meta( $audio->ID, 'your_audio_metas', true );
    // to get the meta values and add them to the var $html like
    // $html .= '<div>your_content</div>';
    return $html;
}
add_filter( 'wp_audio_shortcode', 'wpse_163324_audio_filter', 10, 5 );

Leave a Comment