Show subtitles in Videojs HTML5 Player

The WordPress plugin Videojs HTML5 Player is a great thing. Especially in combination with the Advanced Custom Fields (ACF) or ACF Pro plugin, it is relatively easy to embed videos on a website created with WordPress and design them as desired using CSS. The videos integrated in this way are HTML-confrom, can be easily designed using CSS and react responsively.

One small difficulty is adding subtitles to the videos. Unfortunately, this functionality is not provided by the Videojs HTML5 Player plugin.

Normally, subtitles can be added directly to the video player as CRT or VTT files. The regular syntax for this would be as follows:

<video id="video" controls preload="metadata">
  <source src="video-short.mp4" type="video/mp4" />
  <track
    label="English"
    kind="subtitles"
    srclang="en"
    src="subtitles.vtt"
    default />
</video>

But jQuery makes it relatively easy to add this manually afterwards.

I’m going to assume that several videos are to be integrated on the page. We implement the counter using a simple PHP query and save the current number in the $number variable.

We have to include the actual subtitle text as a VTT file. You may have to generate a VTT file from an SRT file first – but there are tools for this – for example this one here:
www.happyscribe.com/de/untertitel-tools/srt-in-vtt-umwandelnwww.happyscribe.com/de/untertitel-tools/srt-in-vtt-umwandeln

To integrate the subtitles into the player generated by the “Videojs HTML5 Player” plugin, it is sufficient to insert the following code of the respective template. It should be noted that we modify the class of the player via the counter in order to control the player uniquely.

<script>
var video = jQuery('<track />', {
kind: 'captions',
src: '<?PHP echo($untertitel_vtt); ?>',
srclang: 'de',
label: 'Deutsch'
});
video.appendTo(jQuery('.video_<?PHP echo($number); ?> video-js'));

</script>

I use the code to address the video element that is located in the HTML element or in the container with the “video_x” class – the “x” is swapped with the consecutive number of the video that has just been called up.