How to add ‘class’ attribute into shortcode [audio]?

I would like to style two MediaElement players on the same page differently, and figured out the easier way to do this (compared to adding a completely new shortcode and enqueueing a new stylesheet, which I couldn’t get working either) is to assign a different class to the audio shortcode of player A.

The WordPress code reference
mentions adding a class attribute to the shortcode, but I can’t get it to work. For instance, writing



does give me a working player, but I can’t see “miniplayer” assigned to it anywhere in my Firefox console. So how do I assign a class to my shortcode properly?

3 Answers
3

WordPress allows least three options to manipulate the code to your needs.

  1. Use a global variable that you increment with @Jevuska ‘s answer.

    global $my_audio_player_count;
    $my_audio_player_count = 0;
    
    add_filter( 'wp_audio_shortcode_class', 'wpse221201_audio_shortcode_class', 1, 1 );
    function wpse221201_audio_shortcode_class( $class ) {
        global $my_audio_player_count;
        $class .= ' my-audio-player-'.$my_audio_player_count++;
        return $class;
    }
    
  2. Remove the built-in shortcode and add your own

    remove_shortcode('audio');
    add_shortcode('audio', 'my_audio_shortcode');
    
    function my_audio_shortcode($args) {
        //TODO: Insert your own version of the shortcode
    }
    
  3. Use the wp_audio_shortcode_override filter hook to override

    add_filter('wp_audio_shortcode_override', 'my_audio_shortcode');
    
    function my_audio_shortcode($args) {
        //TODO: Insert your own version of the shortcode
    }
    

Leave a Comment