How to embed youtube in custom field buddy press - youtube

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');

Related

Converting youtube/vimeo urls to embedded video

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

How can I confirm a Twitter web intent was sent?

I'd like to confirm a user tweeted after clicking a Twitter Web Intent. How can I accomplish this?
Example:
Tweet
Assuming an anonymous* user clicks this link and tweets, how can I confirm this?
Ideally I'd love to get a link to the tweet.
* anonymous as in not authenticated on my site and without knowing their Twitter username
Update
This solution no longer works after Twitter updated the behaviour of the widgets. You can only track if the tweet button was clicked now, and not if the tweet was actually posted.
You can track tweets using the 'twttr.events.bind' event listener form the Twitter API. A working example of tracking tweets can be found here: http://jsfiddle.net/EZ4wu/3/
HTML:
<i class="icon-twitter-sign icon-white"></i> Tweet
JavaScript:
function reward_user( event ) {
if ( event ) {
alert( 'Tweeted' );
console.log( event );
}
}
window.twttr = (function (d,s,id) {
var t, js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return; js=d.createElement(s); js.id=id;
js.src="//platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs);
return window.twttr || (t = { _e: [], ready: function(f){ t._e.push(f) } });
}(document, "script", "twitter-wjs"));
twttr.ready(function (twttr) {
twttr.events.bind('tweet', reward_user);
});
My previous solution is now outdated and no longer appears to work.
Try this:
twttr.events.bind('loaded', function(event) {
window.location = "http://theredirect_link.com"
});
#Niroj's answer no longer works. They updated the api, so the event listener fires immediately after user clicks the button - you have no way of checking if he actually tweeted.
If you create the window yourself (without using Twitter widgets), you can at least detect if the window was closed (either user closed it or tweeted).
Don't link the widgets api!
HTML:
<a id="twitter-intent" href="https://twitter.com/intent/tweet?url=https://www.webniraj.com/2012/09/11/twitter-api-tweet-button-callbacks/&text=Twitter+API:+Tweet+Button+Callbacks"><i class="icon-twitter-sign icon-white"></i> Tweet</a>
JS:
document.getElementById('twitter-intent').addEventListener('click', function(e) {
e.preventDefault();
e.stopPropagation(); //this should do in case you don't want to unlink twitter widgets api
var width = 575,
height = 400,
left = (screen.width - width) / 2,
top = (screen.height - height) / 2,
url = this.href,
opts = 'status=1' +
',width=' + width +
',height=' + height +
',top=' + top +
',left=' + left;
var win = window.open(url, 'twitter_share', opts);
var timer = setInterval(checkWin, 500);
function checkWin() {
if (win.closed) {
//just assume the user tweeted (he could just close the window without tweeting)
alert("Thank you for tweeting!");
clearInterval(timer);
}
}
});

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
}
?>

PrettyPhoto annd youtube videos overlay

I have a webpage with prettyPhoto and a youtube video inside the web page.
With jquery I do:
$("#youtubevideo embed").attr("wmode", "opaque");
also tried $("#youtubevideo embed").attr("wmode", "transparent");
In firefox image is over the youtube video, but the corners of pretty photo are missing. Not really missing because if I scroll up ad down they are shown. But still they don't appear correctly.
In Chrome video is still on top of the images :( Is there a way to fix this? Thanks
after 2 days of searching the web for the answer i've found a pure JS function that fix it in all browsers!
there you go:
function fix_flash() {
// loop through every embed tag on the site
var embeds = document.getElementsByTagName('embed');
for (i = 0; i < embeds.length; i++) {
embed = embeds[i];
var new_embed;
// everything but Firefox & Konqueror
if (embed.outerHTML) {
var html = embed.outerHTML;
// replace an existing wmode parameter
if (html.match(/wmode\s*=\s*('|")[a-zA-Z]+('|")/i))
new_embed = html.replace(/wmode\s*=\s*('|")window('|")/i, "wmode='transparent'");
// add a new wmode parameter
else
new_embed = html.replace(/<embed\s/i, "<embed wmode='transparent' ");
// replace the old embed object with the fixed version
embed.insertAdjacentHTML('beforeBegin', new_embed);
embed.parentNode.removeChild(embed);
} else {
// cloneNode is buggy in some versions of Safari & Opera, but works fine in FF
new_embed = embed.cloneNode(true);
if (!new_embed.getAttribute('wmode') || new_embed.getAttribute('wmode').toLowerCase() == 'window')
new_embed.setAttribute('wmode', 'transparent');
embed.parentNode.replaceChild(new_embed, embed);
}
}
// loop through every object tag on the site
var objects = document.getElementsByTagName('object');
for (i = 0; i < objects.length; i++) {
object = objects[i];
var new_object;
// object is an IE specific tag so we can use outerHTML here
if (object.outerHTML) {
var html = object.outerHTML;
// replace an existing wmode parameter
if (html.match(/<param\s+name\s*=\s*('|")wmode('|")\s+value\s*=\s*('|")[a-zA-Z]+('|")\s*\/?\>/i))
new_object = html.replace(/<param\s+name\s*=\s*('|")wmode('|")\s+value\s*=\s*('|")window('|")\s*\/?\>/i, "<param name='wmode' value='transparent' />");
// add a new wmode parameter
else
new_object = html.replace(/<\/object\>/i, "<param name='wmode' value='transparent' />\n</object>");
// loop through each of the param tags
var children = object.childNodes;
for (j = 0; j < children.length; j++) {
try {
if (children[j] != null) {
var theName = children[j].getAttribute('name');
if (theName != null && theName.match(/flashvars/i)) {
new_object = new_object.replace(/<param\s+name\s*=\s*('|")flashvars('|")\s+value\s*=\s*('|")[^'"]*('|")\s*\/?\>/i, "<param name='flashvars' value='" + children[j].getAttribute('value') + "' />");
}
}
}
catch (err) {
}
}
// replace the old embed object with the fixed versiony
object.insertAdjacentHTML('beforeBegin', new_object);
object.parentNode.removeChild(object);
}
}
}
now you can just run in when the page loads with jQuery:
$(document).ready(function () {
fix_flash();
}
Also you can add ?wmode=transparent to each youtube link
So if you have code like:
<iframe src="http://www.youtube.com/embed/aoZbiS20HGI">
</iframe>
You need to change it to:
<iframe src="http://www.youtube.com/embed/aoZbiS20HGI?wmode=transparent">
</iframe>

Resources