Skip to content

Instantly share code, notes, and snippets.

@Blackbam
Created May 28, 2019 15:30
Show Gist options
  • Save Blackbam/0ba3ab61511e26020f692e513a8dfe57 to your computer and use it in GitHub Desktop.
Save Blackbam/0ba3ab61511e26020f692e513a8dfe57 to your computer and use it in GitHub Desktop.
Website: Embed external videos by URL from Youtube and Vimeo (PHP, Javascript, HTML)
/**
*
* @param $url
* @return bool|string
*/
function extvideo_embed_code($url) {
if(filter_var($url, FILTER_VALIDATE_URL)) {
$parsed = parse_url($url);
if (in_array($parsed["host"], ["youtube.com", "www.youtube.com", "youtu.be"])) {
if (preg_match('/(?:https?:\/{2})?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\?v=|\/)([^\s&]+)/', $url, $matches)) {
$youtube_id = $matches[1];
return <<<YOUTUBE
<div class="video__youtube" data-youtube>
<img src="https://i.ytimg.com/vi/{$youtube_id}/maxresdefault.jpg" class="video__placeholder" />
<button class="video__button" data-youtube-button="https://www.youtube-nocookie.com/embed/{$youtube_id}?rel=0&showinfo=0&autoplay=1"></button>
</div>
YOUTUBE;
}
} else if (in_array($parsed["host"], ["vimeo.com", "www.vimeo.com"])) {
// we might replace with with an iframe on demand solution like with youtube?
if (preg_match("/(https?:\/\/)?(www\.)?(player\.)?vimeo\.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*/", $url, $output_array)) {
$vimeo_id = $output_array[5];
return '<iframe width="560" height="315" src="https://player.vimeo.com/video/'. $vimeo_id.'" frameborder="0" allowfullscreen></iframe>';
}
}
}
return '<p>'.__('Missing video: Unknown host.','r2ocm').'</p>';
}
(function (window) {
'use strict';
window.code = window.code || {};
window.code.lightweightYoutubePlayer = function () {
var dataYoutubeVideos = '[data-youtube]';
var youtubeVideos = document.querySelectorAll(dataYoutubeVideos);
function init() {
youtubeVideos.forEach(function(element) {
bindYoutubeVideoEvent(element);
});
}
function bindYoutubeVideoEvent(element) {
var button = element.querySelector('[data-youtube-button]');
button.addEventListener('click', createIframe);
}
function createIframe(event) {
var url = event.target.dataset.youtubeButton;
var youtubePlaceholder = event.target.parentNode;
var htmlString = '<div class="video__youtube"><iframe class="video__iframe" src="' + url + '" frameborder="0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></div>';
youtubePlaceholder.style.display = 'none';
youtubePlaceholder.insertAdjacentHTML('beforebegin', htmlString);
youtubePlaceholder.parentNode.removeChild(youtubePlaceholder);
}
return {
init: init
}
};
})(window)
ready();
function ready() {
var lightweightYoutubePlayer = new code.lightweightYoutubePlayer()
if (document.readyState != 'loading') {
page.init()
} else {
document.addEventListener('DOMContentLoaded', lightweightYoutubePlayer.init);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment