# 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.

- Type: PHP
- Runs: Frontend only
- Category: [Performance](https://wpide.com/library/category/performance/)
- Tags: performance, video, embeds
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/click-to-play-youtube/

## Code

```php
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">&#9658;</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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Click-to-Play YouTube Embeds" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
