Converting youtube/vimeo urls to embedded video - youtube

I found this code that converts youtube/vimeo url's into embedded videos.
Javascript - convert youtube/vimeo url's into embed versions for use on a forum comment feature
I am trying to use it in my CMS which uses TinyMCE. TinyMCE wraps paragraph tags around the urls. While this doesn't affect the YouTube url it breaks the Vimeo url.
The fiddle for this is here: http://jsfiddle.net/88Ms2/378/
var videoEmbed = {
invoke: function(){
$('body').html(function(i, html) {
return videoEmbed.convertMedia(html);
});
},
convertMedia: function(html){
var pattern1 = /(?:http?s?:\/\/)?(?:www\.)?(?:vimeo\.com)\/?(.+)/g;
var pattern2 = /(?:http?s?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g;
var pattern3 = /([-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?(?:jpg|jpeg|gif|png))/gi;
if(pattern1.test(html)){
var replacement = '<iframe width="420" height="345" src="//player.vimeo.com/video/$1" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
var html = html.replace(pattern1, replacement);
}
if(pattern2.test(html)){
var replacement = '<iframe width="420" height="345" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>';
var html = html.replace(pattern2, replacement);
}
if(pattern3.test(html)){
var replacement = '<img class="sml" src="$1" /><br />';
var html = html.replace(pattern3, replacement);
}
return html;
}
}
setTimeout(function(){
videoEmbed.invoke();
},3000);
In the fiddle example, if you add paragraph tags around the vimeo url in the html and run the code, it no longer displays the vimeo video. I noticed that a tag or any text before the link is fine, but anything after the link, any text or tag, (on the same line) breaks it.
Any suggestions for how to fix this?
Thank you!

<?php
function videoType($url) {
if (strpos($url, 'youtube') > 0)
{ // https://www.youtube.com/watch?v=YKKMtGhVdhc
$youtube_url = 'https://www.youtube.com/embed/';
// Now get the 'v=' value & stick on the end
preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $matches);
$v = $matches[1];
// Final result
return '<div class="videoWrapper"><iframe src="'. $youtube_url . $v . '" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>';
}
elseif (strpos($url, 'vimeo') > 0)
{ // https://player.vimeo.com/video/116582567
$vimeo_url = 'https://player.vimeo.com/video/';
// Now get the last part of the url
$v = substr( strrchr( $url, '/' ), 1 );
// Final result
return '<div class="videoWrapper"><iframe src="'. $vimeo_url . $v . '" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe></div>';
}
else if (strpos($url, 'matterport') > 0)
{ // https://my.matterport.com/show/?m=uRGXgoiYk9f
$matterport_url = 'https://my.matterport.com/show/';
// Now get the last port of the url
$v2 = (explode("/", $url));
$v = end($v2);
// Fina result
return '<div class="videoWrapper"><iframe src="' . $matterport_url . $v . '" frameborder="0" allowfullscreen allow="vr"></iframe></div>';
}
else
{
return false;
}} ?>
I created a solution above which creates 3 different types of embedded videos in PHP

Related

How to add start time variable to Lite YouTube Embed code created by Amit Agarwal

I use Amit Agarwal code from https://www.labnol.org/internet/light-youtube-embeds/27941/ in my website to lite embeded youtube video.
Is there any way to add start time to the script so that I could load each video with different start time.
<div class="youtube-player" data-id="VIDEO_ID" start-id="TIME"></div>
His complete script are as follows:
<script>
function labnolIframe(div) {
var iframe = document.createElement('iframe');
iframe.setAttribute('src', 'https://www.youtube.com/embed/' + div.dataset.id + '?autoplay=1&rel=0');
iframe.setAttribute('frameborder', '0');
iframe.setAttribute('allowfullscreen', '1');
iframe.setAttribute('allow', 'accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture');
div.parentNode.replaceChild(iframe, div);
}
function initYouTubeVideos() {
var playerElements = document.getElementsByClassName('youtube-player');
for (var n = 0; n < playerElements.length; n++) {
var videoId = playerElements[n].dataset.id;
var div = document.createElement('div');
div.setAttribute('data-id', videoId);
var thumbNode = document.createElement('img');
thumbNode.src='//i.ytimg.com/vi/ID/hqdefault.jpg'.replace('ID', videoId);
div.appendChild(thumbNode);
var playButton = document.createElement('div');
playButton.setAttribute('class', 'play');
div.appendChild(playButton);
div.onclick = function () {
labnolIframe(this);
};
playerElements[n].appendChild(div);
}
}
document.addEventListener('DOMContentLoaded', initYouTubeVideos);
</script>
I have added timeId var into the mix hoping that I could use start-id value to let embed video to start at specific time. It still start at 0 sec of the video.
function labnolIframe(div) {
var iframe = document.createElement('iframe');
iframe.setAttribute('src', 'https://www.youtube.com/embed/' + div.dataset.id + '?start='+ div.dataset.id + '&autoplay=1&rel=0');
iframe.setAttribute('frameborder', '0');
iframe.setAttribute('allowfullscreen', '1');
iframe.setAttribute('allow', 'accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture');
div.parentNode.replaceChild(iframe, div);
}
function initYouTubeVideos() {
var playerElements = document.getElementsByClassName('youtube-player');
for (var n = 0; n < playerElements.length; n++) {
var videoId = playerElements[n].dataset.id;
var timeId = playerElements[n].dataset.id;
var div = document.createElement('div');
div.setAttribute('data-id', videoId);
div.setAttribute('start-id', timeId);
var thumbNode = document.createElement('img');
thumbNode.src = '//i.ytimg.com/vi/ID/hqdefault.jpg'.replace('ID', videoId);
div.appendChild(thumbNode);
var playButton = document.createElement('div');
playButton.setAttribute('class', 'play');
div.appendChild(playButton);
div.onclick = function () {
labnolIframe(this);
};
playerElements[n].appendChild(div);
}
}
document.addEventListener('DOMContentLoaded', initYouTubeVideos);
Just change:
iframe.setAttribute('src', 'https://www.youtube.com/embed/' + div.dataset.id + '?autoplay=1&rel=0');
to:
iframe.setAttribute('src', 'https://www.youtube.com/embed/' + div.dataset.id + '?start=YOUR_START_TIME_IN_SECONDS&autoplay=1&rel=0');
Note the added start=YOUR_START_TIME_IN_SECONDS& in the URL.

How do I put an HTML over Youtube iframe using javascript

How can I access the iframe of a youtube video and use it to layer an html over it? Right now as I access the contentDocument I get a CORS error. Please help if can, below is a code snippet
function onPlayerReady(event) {
var iframe = player.getIframe();
var iframeDocument = iframe.contentDocument;
var pops = document.createElement('div');
pops.innerHTML =
'<div class="bar">' +
'</div>';
iframe.appendChild(pops)
event.target.playVideo();
}

How to embed youtube in custom field buddy press

How do you embed YouTube in a custom field for the user's profile in Buddy Press?
Refer below link, hope this will help you,
http://snippetbarn.bp-fr.net/how-to-embed-a-video-on-profile/
function set_video_field( $field_value ) {
$bp_this_field_name = bp_get_the_profile_field_name();
// field name (case sensitive)
if( $bp_this_field_name == 'Spotlight' ) {
$field_value = strip_tags( $field_value );
// building the HTML and h/w of the iframe
$field_value = '<iframe width="420" height="315" src="http://www.youtube.com/embed/'.$field_value.'" frameborder="0" allowfullscreen></iframe>';
}
return $field_value;
}
add_filter( 'bp_get_the_profile_field_value','set_video_field');

How to correctly use oembed to pull thumbs from youtube

I show a lot of thumbs on my homepage from youtube videos. I was using this function below to grab the thumb from a youtube url which works fast but it doesn't work for url's in the shortned form like youtu.be/JSHDLSKL.
function get_youtube_screen_link( $url = '', $type = 'default', $echo = true ) {
if( empty( $url ) )
return false;
if( !isset( $type ) )
$type = '';
$url = esc_url( $url );
preg_match("|[\\?&]v=([^&#]*)|",$url,$vid_id);
if( !isset( $vid_id[1] ) )
return false;
$img_server_num = 'i'. rand(1,4);
switch( $type ) {
case 'large':
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/0.jpg";
break;
case 'first':
// Thumbnail of the first frame
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/1.jpg";
break;
case 'small':
// Thumbnail of a later frame(i'm not sure how they determine this)
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/2.jpg";
break;
case 'default':
case '':
default:
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/default.jpg";
break;
}
if( $echo )
echo $img_link;
else
return $img_link;
}
So I tried to use Oembed to get the thumbs instead which works for all variations of the youtube url but it retrieves the 480px/360px thumb which causes a lot of cropping to get it down to the 120px/90px size I use to display them. The other issue was it caused my page speed to increase by 4 seconds which Im guessing is a problem with the way I'm implementing it. Here's how I call the thumb inside a loop.
<?php
require_once(ABSPATH.'wp-includes/class-oembed.php');
$oembed= new WP_oEmbed;
$name = get_post_meta($post->ID,'video_code',true);
$url = $name;
//As noted in the comments below, you can auto-detect the video provider with the following
$provider = $oembed->discover($name);
//$provider = 'http://www.youtube.com/oembed';
$video = $oembed->fetch($provider, $url, array('width' => 300, 'height' => 175));
$thumb = $video->thumbnail_url; if ($thumb) { ?>
<img src="<?php echo $thumb; ?>" width="120px" height="90px" />
<?php } ?>
So how should I be doing this to maximize efficiency?
I came across this page from youtube explaining their oembed support, They mentioned that they output to json format so I made a function that gets the json data and then enables you to use it.
Feel free to ask if you need more help.
<?php
$youtube_url = 'http://youtu.be/oHg5SJYRHA0'; // url to youtube video
function getJson($youtube_url){
$baseurl = 'http://www.youtube.com/oembed?url='; // youtube oembed base url
$url = $baseurl . $youtube_url . '&format=json'; // combines the url with format json
$json = json_decode(file_get_contents($url)); // gets url and decodes the json
return $json;
}
$json = getJson($youtube_url);
// from this point on you have all your data placed in variables.
$provider_url = $json->{'provider_url'};
$thumbnail_url = $json->{'thumbnail_url'};
$title = $json->{'title'};
$html = $json->{'html'};
$author_name = $json->{'author_name'};
$height = $json->{'height'};
$thumbnail_width = $json->{'thumbnail_width'};
$thumbnail_height = $json->{'thumbnail_height'};
$width = $json->{'width'};
$version = $json->{'version'};
$author_url = $json->{'author_url'};
$provider_name = $json->{'provider_name'};
$type = $json->{'type'};
echo '<img src="'.$thumbnail_url.'" />'; // echo'ing out the thumbnail image
Ok I came up with a solution from pieces of other questions. First we need to get the id from any type of url youtube has using this function.
function getVideoId($url)
{
$parsedUrl = parse_url($url);
if ($parsedUrl === false)
return false;
if (!empty($parsedUrl['query']))
{
$query = array();
parse_str($parsedUrl['query'], $query);
if (!empty($query['v']))
return $query['v'];
}
if (strtolower($parsedUrl['host']) == 'youtu.be')
return trim($parsedUrl['path'], '/');
return false;
}
Now we can get use YouTube Data API to get the thumbnail from the video id. Looks like this.
<?php
$vid_id = getVideoId($video_code);
$json = json_decode(file_get_contents("http://gdata.youtube.com/feeds/api/videos/$vid_id?v=2&alt=jsonc"));
echo '<img src="' . $json->data->thumbnail->sqDefault . '" width="176" height="126">';
?>
The problem is that is causing an extra 2 seconds load time so I simply use the $vid_id and place it inside http://i3.ytimg.com/vi/<?php echo $vid_id; ?>/default.jpg which gets rid of the 2 seconds added by accessing the youtube api.

Dynamic Youtube Link to open with Colorbox

I am tying to have a link to a youtube video open with colorbox. The link is dynamic - I am pulling the feed from youtube using simplexml.The colorbox shows up on click, but it is blank. Check the URL here: http://revmiller.com/videos-youtube-custom.php for an example. Here is the link's code: <a class='youtube' href="<?php echo $watch; ?>" title="<?php echo $media->group->title; ?>"><img src="<?php echo $thumbnail;?>" /></a>
Thank you very much in advance for any ideas!
I was correct that I should have been calling the embed URL. To do this, I had to extract the video id and plug it into the embed URL for each entry. If anyone is seeking to do something similar, here is the working code (the above link will no longer work - it was for testing only):
<?php
//Credits: Mixed some code from Vikram Vaswani (http://www.ibm.com/developerworks/xml/library/x-youtubeapi/), Matt (http://stackoverflow.com/questions/7221485/get-youtube-video-id-from-url-w-php), & Tim (http://groups.google.com/group/youtube-api-gdata/browse_thread/thread/fc1efc399f9cc4c/d1a48cf5d4389cf8?lnk=gst&q=colorbox#d1a48cf5d4389cf8), and then messed around with it to fit my needs.
function getYoutubeId($ytURL)
{
$urlData = parse_url($ytURL);
//echo '<br>'.$urlData["host"].'<br>';
if($urlData["host"] == 'www.youtube.com') // Check for valid youtube url
{
$query_str = parse_url($ytURL , PHP_URL_QUERY);
parse_str($query_str, $args);
$ytvID = $args['v'];
return $ytvID;
}
else
{
//echo 'This is not a valid youtube video url. Please, give a valid url...';
return 0;
}
}
// set feed URL
$feedURL = 'your feed url here';
// read feed into SimpleXML object
$sxml = simplexml_load_file($feedURL);
?>
<h1 class="page-title">Video Gallery</h1>
<?php
// iterate over entries in feed
foreach ($sxml->entry as $entry) {
// get nodes in media: namespace for media information
$media = $entry->children('http://search.yahoo.com/mrss/');
// get video player URL
$attrs = $media->group->player->attributes();
$watch = $attrs['url'];
// get video thumbnail
$attrs = $media->group->thumbnail[0]->attributes();
$thumbnail = $attrs['url'];
//get video id
$videoid = $yt->videoid[0];
// get <yt:duration> node for video length
$yt = $media->children('http://gdata.youtube.com/schemas/2007');
$attrs = $yt->duration->attributes();
$length = $attrs['seconds'];
// get <yt:stats> node for viewer statistics
$yt = $entry->children('http://gdata.youtube.com/schemas/2007');
$attrs = $yt->statistics->attributes();
$viewCount = $attrs['viewCount'];
// get <gd:rating> node for video ratings
$gd = $entry->children('http://schemas.google.com/g/2005');
if ($gd->rating) {
$attrs = $gd->rating->attributes();
$rating = $attrs['average'];
} else {
$rating = 0;
}
$videoId = getYoutubeId($watch);
?>
<div class="item">
<h1 class="video-title">
<a class="youtube" href="http://www.youtube.com/embed/<?php echo $videoId ?>?rel=0&wmode=transparent"><?php echo $media->group->title; ?></a>
</h1>
<p>
<span class="video-thumbnail">
<a class="youtube" href="http://www.youtube.com/embed/<?php echo $videoId ?>?rel=0&wmode=transparent" title="<?php echo $media->group->title; ?>"><img src="<?php echo $thumbnail;?>" /></a>
<br/>click to view
</span>
</p>
</div>
<?php
}
?>

Resources