YouTube iframe API and WordPress

I’m trying the following code on WordPress post page:

<div id="player"></div>

<script>
    // 2. This code loads the IFrame Player API code asynchronously.
    var tag = document.createElement('script');

    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    // 3. This function creates an <iframe> (and YouTube player)
    //    after the API code downloads.
    var player;
    function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
            height: '390',
            width: '640',
            videoId: 'M7lc1UVf-VE',
            playerVars: { 'autoplay': 1, 'controls': 0 },
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    }

    // 4. The API will call this function when the video player is ready.
    function onPlayerReady(event) {
        event.target.playVideo();
    }

    // 5. The API calls this function when the player's state changes.
    //    The function indicates that when playing a video (state=1),
    //    the player should play for six seconds and then stop.
    var done = false;
    function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING && !done) {
            setTimeout(stopVideo, 6000);
            done = true;
        }
    }
    function playVideo() {
        player.playVideo();
    }
    function pauseVideo() {
        player.pauseVideo();
    }
    function stopVideo() {
        player.stopVideo();
    }
    function loadVideoById(val) {
        player.loadVideoById(val, 0, "large");
    }
</script>

However, nothing was displayed.

Related posts

Leave a Reply

2 comments

  1. This kind of code injection is better done with a Shortcode. Instead of document.createElement, just use wp_enqueue_script to load the Iframe API and the rest of the script is printed by the shortcode. PHP heredoc makes easy to build large configurable HTML strings.

    Shortcode usage inside the post/page would be: [ytplayer id="M7lc1UVf-VE"]

    add_shortcode( 'ytplayer', 'print_yt_player' );
    
    function print_yt_player( $atts ) {
        wp_enqueue_script( 'yt-iframe', 'https://www.youtube.com/iframe_api' );
        $yt_id = $atts['id'];
        $html = <<<HTML
            <div id="player"></div>   
            <script>
                var player, done = false;
                function onYouTubeIframeAPIReady() {
                    player = new YT.Player('player', {
                        height: '390',
                        width: '640',
                        videoId: '$yt_id',
                        playerVars: { 'autoplay': 1, 'controls': 0 },
                        events: {
                            'onReady': onPlayerReady,
                            'onStateChange': onPlayerStateChange
                        }
                    });
                }    
                function onPlayerReady(event) {
                    event.target.playVideo();
                }
                function onPlayerStateChange(event) {
                    if (event.data == YT.PlayerState.PLAYING && !done) {
                        setTimeout(stopVideo, 6000);
                        done = true;
                    }
                }
                function playVideo() {
                    player.playVideo();
                }
                function pauseVideo() {
                    player.pauseVideo();
                }
                function stopVideo() {
                    player.stopVideo();
                }
                function loadVideoById(val) {
                    player.loadVideoById(val, 0, "large");
                }
            </script>
    HTML;
        return $html;
    }
    
  2. Most likely, <p> tags are being inserted when the page/post is saved. Two options:

    1. Disable wpautop
    2. Include the script compressed (on a single line), like this:

      <div id="player"></div>
      <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",{height:"390",width:"640",videoId:"M7lc1UVf-VE",playerVars:{autoplay:1,controls:0},events:{onReady:onPlayerReady,onStateChange:onPlayerStateChange}})}function onPlayerReady(a){a.target.playVideo()}var done=!1;function onPlayerStateChange(a){a.data!=YT.PlayerState.PLAYING||done||(setTimeout(stopVideo,6E3),done=!0)}function playVideo(){player.playVideo()}function pauseVideo(){player.pauseVideo()}function stopVideo(){player.stopVideo()}function loadVideoById(a){player.loadVideoById(a,0,"large")};</script>`