In this tutorial, I will show you how to integrate the Youtube Iframe API with the WordPress Shortcode API to create a shortcode which is able to display a Youtube video anywhere in your WordPress theme.
In the snippet below you will see a working example of the [[youtube]]
shortcode which provides support for passing a video ID and can also support multiple videos per page.
You are able to take complete control of the Youtube player and can use any of the available player parameters or playback events.
<?php | |
add_shortcode( 'youtube', function( $attr ) { | |
$attr = wp_parse_args( $attr, array( | |
'id' => '' | |
) ); | |
ob_start(); | |
?> | |
<script async src="https://www.youtube.com/iframe_api"></script> | |
<script> | |
var players = new Array(); | |
function onYouTubeIframeAPIReady() { | |
var playerDivs = document.getElementsByClassName('ytiframevideo'); | |
for(var i = 0; i < playerDivs.length; i++) { | |
var playerid = playerDivs[i].getAttribute('id'); | |
var vidid = playerDivs[i].getAttribute('vidid'); | |
players[playerid] = new YT.Player(playerid, { | |
videoId: vidid, | |
width: 560, | |
height: 316, | |
playerVars: { | |
'version': 3, | |
'autoplay': 1, | |
'controls': 1, | |
'showinfo': 0, | |
'modestbranding': 1, | |
'loop': 1, | |
'playlist': '<?php echo $attr['id']; ?>', | |
'rel': 0, | |
'fs': 0, | |
'cc_load_policty': 0, | |
'iv_load_policy': 3 | |
}, | |
events: { | |
'onReady': function (e) { | |
e.target.mute(); | |
//e.target.setVolume(50); // YOU CAN SET VALUE TO 100 FOR MAX VOLUME. | |
} | |
} | |
}); | |
} | |
} | |
</script> | |
<div class="embed-container"> | |
<!-- <div id="youtubediv"></div> --> | |
<div id="player-<?php echo $attr['id']; ?>" vidid="<?php echo $attr['id']; ?>" class="ytiframevideo"></div> | |
</div> | |
<?php | |
return ob_get_clean(); | |
} ); |
Hope this helps you!
Leave a Reply