Skip to content

Instantly share code, notes, and snippets.

@flowtwo
Last active December 21, 2015 16:08
Show Gist options
  • Save flowtwo/6331154 to your computer and use it in GitHub Desktop.
Save flowtwo/6331154 to your computer and use it in GitHub Desktop.
This YouTube shortcode for WordPress automatically grabs a video's thumbnail, stores it locally and presents the video as a clickable div with a responsive and lazy loading background. I found this useful after having paid a heavy loadtime on my archive of favourite YouTubes.
// Build lazy loading function - visible that is...
(function ($) {
$.fn.visible = function (partial, hidden) {
var $t = $(this).eq(0),
t = $t.get(0),
$w = $(window),
viewTop = $w.scrollTop(),
viewBottom = viewTop + $w.height(),
_top = $t.offset().top,
_bottom = _top + $t.height(),
compareTop = partial === true ? _bottom : _top,
compareBottom = partial === true ? _top : _bottom,
clientSize = hidden === true ? t.offsetWidth * t.offsetHeight : true;
return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop));
};
})(jQuery);
// Run the lazy loading
$(window).on("load resize scroll", function (e) {
$('.lazy-wrapper:not(.loaded)').each(function () {
if ($(this).visible(true)) {
$(this).css('background-image', 'url(' + $(this).data(original) + ')');
$(this).addClass('loaded');
}
});
});
// Load YouTube on user click
$(document).ready(function($) {
$('.video-btn').on('click', function() {
var self = $(this).parent();
if ( self.hasClass('lazy-youtube') ) {
var ID = $(self).attr('data-id');
var HOME = '<?php home_url( "/" ) ?>';
var YOUTUBE = '<div id="wrap-video"><iframe type="text/html" class="video-embed lazy-video" width="640" height="360" src="http://www.youtube.com/embed/' + ID + '?modestbranding=1&autoplay=1&autohide=1&controls=2&theme=dark&showinfo=0&rel=0&enablejsapi=1&origin=' + HOME + '" frameborder="0" seamless webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe></div>';
self.html(YOUTUBE);
}
});
});
<?
/**
* Get YouTube ID by URL
*/
function gr_youtube_id($url) {
$pattern = '#^(?:https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch\?v=|/watch\?.+&v=))([\w-]{11})(?:.+)?$#x';
preg_match($pattern, $url, $matches);
return (isset($matches[1])) ? $matches[1] : false;
}
/**
* Build fragment caching
*/
function gr_cache($key, $time = 3600, $function) {
if (
is_user_logged_in()
) {
call_user_func($function);
return;
}
$key = apply_filters('fragment_cache_prefix','gr_cache_'). $key;
$output = get_transient( $key );
if ( empty( $output ) ) {
ob_start();
call_user_func( $function );
$output = ob_get_clean();
set_transient( $key, $output, $time );
}
echo $output;
}
/**
* Get YouTube thumb by URL and save it locally. Than pass it as data-variables for lazy loading.
*/
function gr_youtube_lazy( $url = NULL ) {
$id = gr_youtube_id( $url );
global $url, $id;
gr_cache('youtube_'. $id, 86400, function() {
$upload = wp_upload_dir();
$path = $upload['basedir'].'/cache';
$thumb_path = $upload['basedir'].'/cache/youtube-'. $id .'.jpg';
$thumb_path_uri = $upload['baseurl'].'/cache/youtube-'. $id .'.jpg';
if ( !file_exists($path) ) {
mkdir($path, 0777, true);
}
if ( file_exists( $thumb_path ) ) {
$thumb = $thumb_path_uri;
} else {
$json = json_decode( file_get_contents('http://gdata.youtube.com/feeds/api/videos/'. $id .'?v=2&alt=jsonc' ) );
$thumb = $json->data->thumbnail->hqDefault;
if ( $thumb ) {
$img_path = file_get_contents( $thumb );
$img_save = file_put_contents( $thumb_path, $img_path );
}
}
$video = '';
$video .= '<div';
$video .= ' class="lazy-wrapper video-wrapper lazy-youtube ratio-wrapper ratio-16x9"';
$video .= ' data-original="'. $thumb .'"';
$video .= ' data-id="'. $id .'"';
$video .= '>';
$video .= '<div class="video-btn"></div>';
$video .= '<div class="ratio-expander"></div>';
$video .= '</div>';
return $video;
});
}
/**
* Build shortcode
*/
function gr_youtube_shortcode($atts, $content = NULL) {
extract( shortcode_atts( array(
'url' => ''
), $atts ) );
ob_start();
if ( $url ) {
echo gr_youtube_lazy( $url );
}
$content = ob_get_contents();
ob_end_clean();
return $content;
}
add_shortcode('youtube', 'gr_youtube_shortcode');
.video-wrapper{
padding-top:56.25%;
position:relative;
background-color:#000;
-webkit-background-size:cover;
-moz-background-size:cover;
-o-background-size:cover;
background-size:cover;
background-position:center;
background-repeat:no-repeat;
}
.video-wrapper .video-btn{
position:absolute;
z-index:99;
left:50%;
top:50%;
margin:-40px 0 0 -50px;
width:100px;
height:80px;
background:url('../../images/video.png') top center no-repeat;
}
.video-wrapper .video-btn:hover{
background-position:bottom;
cursor:pointer;
}
.expander,
.video-embed{
position:absolute;
left:0;
top:0;
width:100%;
height:100%;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment