This type of code injection is best done using Shortcode . Instead of document.createElement just use wp_enqueue_script to load the Iframe API, and the rest of the script is printed in short code. PHP heredoc makes it easy to create large custom HTML strings.
Using a short code inside a post / page will 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; }
source share