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 );