Come Sostituire i Video YouTube con una Miniatura "Clicca per Riprodurre"?
Uso molti video incorporati (tramite oembed) nel mio blog, e questo può rallentare il caricamento delle pagine.
Esiste un modo per sostituire automaticamente i video di YouTube (e altri) con una miniatura (preferibilmente l'immagine in evidenza dell'articolo) e poi sostituire la miniatura con l'iframe del video quando viene cliccata?
Note
- Soluzione per YouTube e Vimeo.
- Utilizza l'immagine in evidenza o la miniatura predefinita del provider video.
- Se più di un oEmbed è presente nella stessa pagina, l'uso dell'immagine in evidenza provoca miniature duplicate.
- Il post deve essere aggiornato prima di vedere le modifiche.
- Da fare: dimensioni di <iframe>e<img>, altri oEmbed.
Fonti di Ispirazione
oEmbed
Sostituire Immagine con Embed
https://stackoverflow.com/q/838878/1287812
Plugin
<?php
/**
 * Plugin Name: oEmbed Sostituisci Iframe con Immagine AutoPlay
 * Plugin URI: https://wordpress.stackexchange.com/q/73996/12615
 * Description: Sostituisce l'embed iFrame con l'Immagine in Evidenza 
 * e se non esiste la sostituisce con la Miniatura del Video
 * Version: 1.0
 * Author: brasofilo
 * Author URI: https://wordpress.stackexchange.com/users/12615/brasofilo
 */
//evita chiamate dirette a questo file
if (!function_exists ('add_action')) {
        header('Status: 403 Forbidden');
        header('HTTP/1.1 403 Forbidden');
        exit();
}
add_filter( 'oembed_dataparse', 'wpse_73996_oembed_click2play', 10, 3 );
function wpse_73996_oembed_click2play( $return, $data, $url ) 
{
    // Crea un ID univoco, nel caso più di un oEmbed sia usato nella pagina 
    // https://stackoverflow.com/questions/3656713/
    $uuid = gettimeofday();
    $uuid = mt_rand() . $uuid['usec'];
    // Usa l'Immagine in Evidenza, se esiste
    // Questo funziona visivamente solo con 1 oEmbed per post
    $post_thumbnail_id = get_post_thumbnail_id( $_REQUEST['post'] );
    if( $post_thumbnail_id )
    {
        $thumb = wp_get_attachment_image_src( $post_thumbnail_id, 'medium' );
        $image = $thumb[0];
    }
    if( !$image ) 
        $image = $data->thumbnail_url; 
    // YouTube
    if ( $data->provider_name == 'YouTube' ) 
    {
        $autoplay = str_replace('feature=oembed', 'feature=oembed&autoplay=1', $return );
        $return = '<script type="text/javascript">var embedCode' 
            . $uuid . ' = \''
            . $autoplay .'\';</script><div id="videocontainer' 
            . $uuid . '"><img src="'
            . $image
            . '" onclick="document.getElementById(\'videocontainer'
            . $uuid . '\').innerHTML = embedCode'
            . $uuid . ';" height="360" width="480" /></div>';
    }
    // Vimeo
    elseif ( $data->provider_name == 'Vimeo' ) 
    {
        $autoplay = str_replace('" width=', '?autoplay=1" width=', $return );
        $return = '<script type="text/javascript">var embedCode'
            . $uuid . ' = \''
            . $autoplay . '\';</script><div id="videocontainer'
            . $uuid . '"><img src="'
            . $image
            .'" onclick="document.getElementById(\'videocontainer'
            . $uuid . '\').innerHTML = embedCode'
            . $uuid . ';" height="360" width="480" /></div>';
    }
    return $return;
}
Contenuti di $data restituiti dai provider video
stdClass(
    type = 'video'
    version = 1.0
    provider_name = 'Vimeo'
    provider_url = 'http://vimeo.com/'
    title = 'Earth'
    author_name = 'Michael König'
    author_url = 'http://vimeo.com/michaelkoenig'
    is_plus = 1
    html = '<iframe src="http://player.vimeo.com/video/32001208" width="540" height="304" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'
    width = 540
    height = 304
    duration = 300
    description = 'lorem ipsum'
    thumbnail_url = 'http://b.vimeocdn.com/ts/307/031/307031094_295.jpg'
    thumbnail_width = 295
    thumbnail_height = 166
    video_id = 32001208
)
stdClass(
    provider_url = 'http://www.youtube.com/'
    thumbnail_url = 'http://i2.ytimg.com/vi/552yWya5RgY/hqdefault.jpg'
    title = 'Tu cara me suena - Arturo Valls imita a Rihanna'
    html = '<iframe width="540" height="304" src="http://www.youtube.com/embed/552yWya5RgY?fs=1&feature=oembed" frameborder="0" allowfullscreen></iframe>'
    author_name = 'antena3'
    height = 304
    thumbnail_width = 480
    width = 540
    version = 1.0
    author_url = 'http://www.youtube.com/user/antena3'
    provider_name = 'YouTube'
    type = 'video'
    thumbnail_height = 360
)
 
                                Amico, grazie mille per questo! Non hai idea di quanto mi sia stato d'aiuto. Dovresti mettere questo plugin sul sito wordpress.org.
 Richard
                            Richard
                        Per tua informazione: ho trovato un trucco incredibilmente semplice su Stackoverflow per fare overlay di immagini con CSS <img style="background:url(thumbnail1.jpg)" src="magnifying_glass.png" /> --> http://stackoverflow.com/questions/403478/css-how-to-overlay-images
 Richard
                            Richard
                        Sì, avevo pensato a quell'icona di overlay "play" ma non ho cercato. Bella aggiunta!
 brasofilo
                            brasofilo
                        Ecco la versione migliorata del plugin brasofilo:
add_filter( 'oembed_dataparse', function($str, $data, $url) {
    if ( ($yt = $data->provider_name == 'YouTube') || ($vm = $data->provider_name == 'Vimeo') ) 
    {
        if($yt) $html = str_replace('feature=oembed', 'feature=oembed&autoplay=1', $str);
        else $html = str_replace('" width=', '?autoplay=1" width=', $str);
        $html = htmlentities($html, ENT_QUOTES);
        $img = $data->thumbnail_url; 
        $title = esc_attr($data->title);
        return '<img src="'. $img . '" onclick="this.outerHTML=\'' . $html . '\'" title="' . $title . '">';
    }
    return $str;
}, 10, 3);
Non dimenticare di pulire la cache oembed! Puoi usare questo comando SQL per farlo:
DELETE FROM wp_postmeta WHERE meta_key LIKE '_oembed%'
Maggiori informazioni su https://siteorigin.com/clearing-oembed-cache/
 
                                Questo è un buon metodo...ma uno meno complicato (per quelli di noi meno esperti) sarebbe usare questo tutorial.
Non inserire il codice di incorporamento di YouTube così come lo fornisce YT (YouTube) (puoi provare, ma risulterà malfunzionante)...invece sostituisci semplicemente la sorgente dal codice di incorporamento del tuo video FINO A &autoplay=1 (lascialo alla fine così com'è).
es.
codice originale fornito da YT:
<object width="420" height="315">
    <param name="movie" value="//www.youtube.com/v/5mEymdGuEJk?hl=en_US&version=3"></param>
    <param name="allowFullScreen" value="true"></param>
    <param name="allowscriptaccess" value="always"></param>
    <embed src="//www.youtube.com/v/5mEymdGuEJkhl=en_US&version=3" type="application/x-shockwave-flash" width="420" height="315" allowscriptaccess="always" allowfullscreen="true"></embed>
</object>
Codice usato nel tutorial con la stessa sorgente YT:
<object width="420" height="315" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0">
    <param name="allowFullScreen" value="true" />
    <param name="allowscriptaccess"value="always" />
    <param name="src" value="http://www.youtube.com/v/5mEymdGuEJk?version=3&hl=en_US&autoplay=1" /><param name="allowfullscreen" value="true" />
    <embed width="420" height="315" type="application/x-shockwave-flash" src="http://www.youtube.com/v/5mEymdGuEJk?version=3&hl=en_US&autoplay=1" allowFullScreen="true" allowscriptaccess="always" allowfullscreen="true" />
</object>
A parte questo, sostituisci semplicemente la sorgente e il percorso dell'immagine con i tuoi, e voilà!
 
                                Prova questo codice. Copia e incolla semplicemente in un file HTML.
<!DOCTYPE html>
<html>
<body>
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script>
        var tag = document.createElement('script');
        tag.src = "https://www.youtube.com/iframe_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
        var player;
        function onYouTubeIframeAPIReady() {
            player = new YT.Player('player', { // "player" è l'id del contenitore del player YouTube dove viene inserito il video usando l'API iframe di YouTube.
                height: '390',
                width: '640',
                videoId: 'M7lc1UVf-VE',
                events: {
                    'onReady': onPlayerReady, // all'evento onReady verrà chiamata la funzione di callback "onPlayerReady".
                }
            });
        }
        function onPlayerReady(event) { // quando il player YouTube sarà pronto
            $('#play_vid').click(function() {  // aspetterà il click sull'overlay/immagine
                event.target.playVideo();  // quando si clicca sull'immagine overlay, il video parte.
            });
        }
        $(document).ready(function() {
            $('#player').hide(); // al caricamento del documento il player YouTube sarà nascosto.
            $('#play_vid').click(function() {  // quando l'utente clicca sull'immagine overlay.
                $('#player').show();    // il player diventerà visibile all'utente 
                $('#play_vid').hide(); // e l'immagine overlay verrà nascosta.
            });
        });
    </script>
    <div id="player"></div> <!-- Contenitore del player YouTube -->
    <img id="play_vid" src="PERCORSO_DELLA_TUA_IMMAGINE" /> <!-- immagine overlay che appare davanti al video YouTube. Quando l'utente clicca su questa, l'immagine verrà nascosta e il video partirà usando l'API di YouTube. -->
</body>
</html>
 
                                Cosa fa esattamente questo codice e come risolve il problema? Fai una [modifica] e spiega correttamente cosa fa il tuo codice e come funziona
 Pieter Goosen
                            Pieter Goosen
                        Il codice è stato aggiornato con i commenti. Quando la pagina è pronta, il video di YouTube sarà nascosto e l'immagine di overlay sarà visibile all'utente. Quando l'utente clicca sull'immagine, questa verrà nascosta e il video di YouTube verrà riprodotto e mostrato all'utente.
 Muhammad Azeem
                            Muhammad Azeem