Skip to content

Instantly share code, notes, and snippets.

@yuriitaran
Last active February 14, 2018 23:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuriitaran/e2d0fb0f838a306c59da145e3169e237 to your computer and use it in GitHub Desktop.
Save yuriitaran/e2d0fb0f838a306c59da145e3169e237 to your computer and use it in GitHub Desktop.
WP Fancybox 2 + Youtube video
// functions.php
wp_enqueue_script( 'youtube', 'http://www.youtube.com/player_api', null, null, true ); /* This loads the YouTube IFrame Player API code */
// link, button
$url = $link['url'];
if ( ! ( $btn_class = $link['class'] ) ) {
$btn_class = 'button learn-more';
}
if (preg_match("/youtu/i", $url)) {
$btn_class .= ' fancybox fancybox.iframe';
}
if ( ! ( $title = $link['title'] ) ) {
$title = __( 'LEARN MORE', 'ulf-update' );
}
echo '<a target="' . $target . '" class="' . $btn_class . '" href="' . $url . '">' . $title . '</a>';
// main JS file
/*
* YouTube API for embed player
*/
// Fires whenever a player has finished loading
function onPlayerReady(event) {
event.target.playVideo();
}
// Fires when the player's state changes.
function onPlayerStateChange(event) {
// Go to the next video after the current one is finished playing
if (event.data === 0) {
jQuery.fancybox.next();
}
}
// The API will call this function when the page has finished downloading the JavaScript for the player API
function onYouTubePlayerAPIReady() {
// Initialise the fancyBox after the DOM is loaded
jQuery(document).ready(function() {
jQuery(".fancybox")
.attr('rel', 'gallery')
.fancybox({
openEffect : 'none',
closeEffect : 'none',
nextEffect : 'none',
prevEffect : 'none',
padding : 0,
margin : 50,
beforeShow : function() {
// Find the iframe ID
var id = jQuery.fancybox.inner.find('iframe').attr('id');
// Create video player object and add event listeners
var player = new YT.Player(id, {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment