Video shortcode – autoplay all videos

I ran into this problem while trying to make HTML videos behave like GIFs. WordPress’s built-in video player uses HTML video elements but does not allow videos to play simultaneously.

Instead of using the default WordPress video player (which is best used for more standard video content), I chose to manually use the <video> element via a custom shortcode. For the best compatibility (especially on mobiles) we should also make sure the videos are also muted.

After adding the following code, simply use:

[videogif mp4="http://path_to_file.mp4"]

And you’ll have a nice video working. To control styling and add (basic) HTML video controls, use something like:

[videogif mp4="http://path_to_file.mp4" style="width: 80%" controls="1"]

Code

Add to your functions.php:

// Video gif shortcode
function videogif($atts = [])
{
    // normalize attribute keys, lowercase
    $atts = array_change_key_case((array)$atts, CASE_LOWER);

    // override default attributes with user attributes
    $wporg_atts = shortcode_atts([
            'mp4' => $atts['mp4'],
            'style' => null,
            'controls' => False
        ], $atts);

    // build output
    $o = '';
    $o .= '<video autoplay loop muted playsinline ';
    if ($wporg_atts['controls']) $o .= 'controls ';
    $o .= 'class="videogif"';
    if (!is_null($wporg_atts['style'])) $o .= 'style="' . $wporg_atts['style'] . '" ';
    $o .= '><source src="' . $wporg_atts['mp4'] . '" type="video/mp4" />';
    $o .= '<p>Your browser does not support the video element.</p></video>';

    // return output
    return $o;
}
add_shortcode( 'videogif', 'videogif' );

I also use the following CSS to resize and center the videos by default:

/* Center videogif by default */
.videogif {
    width: 100%;
    display:block;
    margin: 0 auto;
}