­
Posted by on Mar 31, 2016 in Development, Javascript, PHP | No Comments

Well, that title is a mouthful, let me explain. Recently I had the need to create a shortcode to embed YouTube videos, no problem right? Well, lets introduce a few more variables. First we want to fire custom Google Analytics events on video play, pause and complete which is easy enough to work into the shortcode. If we use the YouTube JavaScript API instead of iframe embed it’s very simple to fire custom events, there are plenty of examples out there. But in addition, the shortcode also needed to be able to be used numerous times on a page. Below is my solution, feel free to comment if you want to improve on or have questions about any of the code.

The solution assumes a shortcode like [youtube id='YouTubeVideoId' width='664' height='375'] where width and height are optional as I have defaults set.

<?php
function show_youtube($atts){
extract(shortcode_atts(array(
'id' => '',
'height' => '315',
'width' => '560',
),
$atts));
if($id != ''){
$uid = uniqid('youtube-video-');
ob_start();
?>
<div id="<?php echo $uid;?>"></div>
<script>
var exists = false;
var scripts = document.getElementsByTagName('script');
for(var i=0;i<scripts.length;i++){
if(scripts[i].src=='http://www.youtube.com/player_api'){
exists = true;
}
}
if(!exists){
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onYouTubePlayerAPIReady(){
function setupVid(vid){
return new YT.Player(vid.id, {
playerVars: {
modestbranding: true,
theme: 'light',
rel: 0
},
height: vid.height,
width: vid.width,
videoId: vid.vidId,
events: {
'onStateChange': onPlayerStateChange
}
});
}
for(var i=0;i<playerList.length;i++){
var player = setupVid(playerList[i]);
}
}
var lastAction = '';
function onPlayerStateChange(event){
title = event.target.F.videoData.title;
switch (event.data){
case YT.PlayerState.PLAYING:
ga('send', 'event', 'Video', 'Started', title);
break;
case YT.PlayerState.ENDED:
ga('send', 'event', 'Video', 'Completed', title);
break;
case YT.PlayerState.PAUSED:
if(lastAction != 'paused'){
ga('send', 'event', 'Video', 'Paused', title);
}else{
lastAction = 'paused';
}
break;
}
}
var playerList = [];
}
playerList.push({id: '<?php echo $uid;?>', height: '<?php echo $height;?>', width: '<?php echo $width;?>', vidId: '<?php echo $id;?>'})
</script>
<?php
return ob_get_clean();
}else{
return "<p>No Video ID Specified</p>";
}
}
add_shortcode('youtube', 'show_youtube');
?>

Tagged: , , , , ,