Is it possible to enqueue the Youtube API script or does it have to be inline?

The code below is the main part of a function in my functions.php which returns a div and script which ultimately output a youtube API iframe to the template where the code had been called from. At the moment it’s working fine; however I would like to enqueue the javascript, or at least move it out of my PHP code. I tired moving it to my main JavaScript file ( which is enqueued in the footer ) but it doesn’t work when I move it there. Edit: I had hardcoded the vars to avoid having to use wp_localize_script so as to out of the picture.

Surely there’s a better way ( or WordPress way ) of doing this?

$return = '

    <div id="' . $postid . 'player"></div>

    <script> var tag = document.createElement("script"); tag.src = "http://www.youtube.com/player_api";
    var firstScriptTag = document.getElementsByTagName("script")[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    var player;
    function onYouTubePlayerAPIReady() {
        player = new YT.Player("'. $postid .'player", {
            height: "315",
            width: "560",
            videoId: "'. $videoID .'",
        });
    }
    </script>

    ';

return $return;

1
1

First, make sure the YT api is enqueued() and added to the footer.

function wp_enqueue_scripts__youtube_api() {
    wp_enqueue_script( 'yt-player-api', 'http://www.youtube.com/player_api', array(), false, true );
}

add_action( 'wp_enqueue_scripts', 'wp_enqueue_scripts__youtube_api' );

Next, output your div somewhere on the page.

<div id="' . $postid . 'player"></div>

Then, hook into wp_footer and make sure you set the priority higher that 20. By then the script should be rendered on the page and you can double check with wp_script_is().

function wp_footer__youtube_api() {
    if ( wp_script_is( 'yt-player-api', 'done' ) ) {
        $postid  = 123;
        $videoID = 123;
        ?>
        <script id="yt-player-api-ready" type="text/javascript">
            var player;
            function onYouTubePlayerAPIReady() {
                player = new YT.Player("<?php echo $postid; ?>player", {
                    height: "315",
                    width: "560",
                    videoId: "<?php echo $videoID ?>"
                });
            }
        </script>
        <?php
    }
}

add_action( 'wp_footer', 'wp_footer__youtube_api', 20 );

Leave a Comment