Click-to-Play YouTube Embeds
Shows a lightweight thumbnail instead of the full YouTube player until the visitor clicks play, saving around a megabyte of scripts per video.
Opens WPIDE on
Code
add_filter( 'embed_oembed_html', function ( $html, $url ) {
if ( is_feed() || wp_is_json_request() || ! preg_match( '#(?:youtube\.com/(?:watch\?v=|embed/|shorts/)|youtu\.be/)([A-Za-z0-9_-]{11})#', $url, $match ) ) {
return $html;
}
$id = $match[1];
$title = preg_match( '/title="([^"]*)"/', $html, $t ) ? html_entity_decode( $t[1], ENT_QUOTES ) : 'YouTube video';
$GLOBALS['wpide_lite_youtube_used'] = true;
return sprintf(
'<div class="wpide-yt" data-id="%1$s" data-title="%2$s" style="position:relative;aspect-ratio:16/9;background:#000 url(https://i.ytimg.com/vi/%1$s/hqdefault.jpg) center/cover no-repeat;cursor:pointer">' .
'<button type="button" aria-label="%3$s" style="position:absolute;inset:0;margin:auto;width:68px;height:48px;border:0;border-radius:12px;background:rgba(255,0,0,.9);color:#fff;font-size:22px;cursor:pointer">►</button></div>',
esc_attr( $id ),
esc_attr( $title ),
esc_attr( 'Play: ' . $title )
);
}, 10, 2 );
add_action( 'wp_footer', function () {
if ( empty( $GLOBALS['wpide_lite_youtube_used'] ) ) {
return;
}
?>
<script>
document.addEventListener( 'click', function ( event ) {
var box = event.target.closest( '.wpide-yt' );
if ( ! box ) {
return;
}
var frame = document.createElement( 'iframe' );
frame.src = 'https://www.youtube-nocookie.com/embed/' + encodeURIComponent( box.dataset.id ) + '?autoplay=1';
frame.title = box.dataset.title;
frame.allow = 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture';
frame.allowFullscreen = true;
frame.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;border:0';
box.innerHTML = '';
box.appendChild( frame );
} );
</script>
<?php
} );
Notes
Works for YouTube links in posts and Embed blocks, loading the thumbnail from i.ytimg.com and the player from youtube-nocookie.com.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.