As most people know, wordpress uses oembed to fetch the embed code for videos when adding a youtube video to a post. For example, pasting:
https://www.youtube.com/watch?v=pATcvr3zAhg
Would output this in the html:
<iframe width="420" height="315" src="https://www.youtube.com/embed/pATcvr3zAhg" frameborder="0" allowfullscreen></iframe>
I want to change this markup so it uses fancybox and an image, so my markup should look like this:
<a class="fancybox.iframe various" href="VIDEO SOURCE"><img src="IMAGE HERE"></a>
I was using this code which originally replaced the video with an image and when clicked, changed to the video - however, I want to modify this code now so that it outputs the markup above.
add_filter( 'oembed_dataparse', function($str, $data, $url) {
if ( ($yt = $data->provider_name == 'YouTube') || ($vm = $data->provider_name == 'Vimeo') )
{
if($yt) $html = str_replace('feature=oembed', 'feature=oembed&autoplay=1', $str);
else $html = str_replace('" width=', '?autoplay=1" width=', $str);
$html = htmlentities($html, ENT_QUOTES);
$img = $data->thumbnail_url;
$title = esc_attr($data->title);
return '<img src="'. $img . '" onclick="this.outerHTML=\'' . $html . '\'" title="' . $title . '">';
}
return $str;
}, 10, 3);
Related
I am creating a Chat and i have a function that takes a vimeo url and convert it into an embeded video and it works. The problem is that, when i add any other text to the string, it does not work meanwhile i would like to keep the text around it and still convert the vimeo link into and embeded video
This is my code that convert any vimeo link into an embeded video
<?php
function convertVimeo($url)
{
########################################################
//extract the ID
if(preg_match(
'/\/\/(www\.)?vimeo.com\/(\d+)($|\/)/',
$url,
$matches
))
{
//Si l'url de vimeo est trouve
//the ID of the Vimeo URL: 71673549
$id = $matches[2];
//set a custom width and height
$width = '640';
$height = '360';
//echo the embed code and wrap it in a class
return '<div class="videowrapper well"><iframe src="http://player.vimeo.com/video/'.$id.'?title=0&byline=0&portrait=0&badge=0&color=ffffff" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe></div>';
}
//Fin de si l'url de vimeo est trouve
########################################################
}
//store the URL into a variable
$message = 'https://vimeo.com/33881199';
$message = convertVimeo($message);
echo $message;
?>
The code above works perfectly but when i do
<?php
//store the URL into a variable
$message = 'Some text before https://vimeo.com/33881199 and text after ';
$message = convertVimeo($message);
echo $message;
?>
It does not work anymore
How to make it keep the text around the video and yet display the video ?
The answer is : Use preg_replace_callback()
Try this :
$doConvert = function($url) {
return convertVimeo($url[0]);
};
$message = preg_replace_callback('#https://vimeo.com/\d*#', $doConvert, $message);
echo $message;
The script will replace and apply you function convertVimeo for each pattern url vimeo.
my solution for youtube link and vimeo link, i'm feel ok
function convertLinkToEmbed($videoLink, $width, $height)
{
$embed = '';
if (preg_match('/https:\/\/(?:www.)?(youtube).com\/watch\\?v=(.*?)/', $videoLink))
$embed = preg_replace("/\s*[a-zA-Z\/\/:\.]*youtube.com\/watch\?v=([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i", "<iframe width=\"" . $width . "\" height=\"" . $height . "\" src=\"//www.youtube.com/embed/$1\" frameborder=\"0\" allowfullscreen></iframe>", $videoLink);
if (preg_match('/https:\/\/vimeo.com\/(\\d+)/', $videoLink, $regs))
$embed = '<iframe src="http://player.vimeo.com/video/' . $regs[1] . '?title=0&byline=0&portrait=0&badge=0&color=ffffff" width="' . $width . '" height="' . $height . '" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>';
return $embed;
}
A quick function for generating embed URL.
public function generateVideoEmbedUrl($url){
//This is a general function for generating an embed link of an FB/Vimeo/Youtube Video.
$finalUrl = '';
if(strpos($url, 'facebook.com/') !== false) {
//it is FB video
$finalUrl.='https://www.facebook.com/plugins/video.php?href='.rawurlencode($url).'&show_text=1&width=200';
}else if(strpos($url, 'vimeo.com/') !== false) {
//it is Vimeo video
$videoId = explode("vimeo.com/",$url)[1];
if(strpos($videoId, '&') !== false){
$videoId = explode("&",$videoId)[0];
}
$finalUrl.='https://player.vimeo.com/video/'.$videoId;
}else if(strpos($url, 'youtube.com/') !== false) {
//it is Youtube video
$videoId = explode("v=",$url)[1];
if(strpos($videoId, '&') !== false){
$videoId = explode("&",$videoId)[0];
}
$finalUrl.='https://www.youtube.com/embed/'.$videoId;
}else if(strpos($url, 'youtu.be/') !== false){
//it is Youtube video
$videoId = explode("youtu.be/",$url)[1];
if(strpos($videoId, '&') !== false){
$videoId = explode("&",$videoId)[0];
}
$finalUrl.='https://www.youtube.com/embed/'.$videoId;
}else{
//Enter valid video URL
}
return $finalUrl;
}
I wrote a function of a combination of answers here to make it very simpleto use.
Only works for plain vimeo links but if this floats your boat:
public function linkURLs( $text )
{
$text = preg_replace('#https?://(www\.)?vimeo\.com/(\d+)#',
'<iframe class="videoFrame" src="//player.vimeo.com/video/$2" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>',
$text);
return $text;
}
Below is the PHP code for the images section in my website using the Cute slider plugin. I am trying to add alt text by adding text to the line $data .= '<img '.$src.''.$datasrc.''.$thumb.'>'; but the alt text ends up duplicated. Where should I add the alt text?
if($layerkey == 0) {
$src = ' src="'.$layer['properties']['image'].'"';
$datasrc = '';
}
else {
$src = ' src="'.$GLOBALS['csPluginPath'].'/img/blank.png" width="1" height="1" alt="Blank"';
$datasrc = ' data-src="'.$layer['properties']['image'].'"';
}
$data .= '<li data-delay="'.$layer['properties']['slidedelay'].'" data-src="'.$layer['properties']['slidedelay'].'" data-trans3d="'.$layer['properties']['3d_transitions'].'" data-trans2d="'.$layer['properties']['2d_transitions'].'">';
$data .= '<img '.$src.''.$datasrc.''.$thumb.'>';
The full php file is here : http://pastie.org/9167151
On this line: $src = ' src="'.$GLOBALS['csPluginPath'].'/img/blank.png" width="1" height="1" alt="Blank"'; alt is already defined, that is why you get two definitions when you try to add it in the second place. You should change the definition on that line instead of on the $data .= '<img '.$src.''.$datasrc.''.$thumb.'>'; line.
i have a posting feature on my site that can embed links and youtube videos. the problem is, that the two clash together, and the youtube iframe ends up being a 404 page on my site. my codes for the youtube videos and links are below, but im not sure how to stop them from combining and ruining it.
by combining, i mean this http://www.youtube.com/watch?v=VhqiT2nWCVU turns to
<iframe src="http://www.youtube.com/watch?v=VhqiT2nWCVU">
which then turns into
<iframe src="">
sorry if i am unclear in any way. my codes are below.
function youtube($string)
{
return preg_replace(
'#(http://(www.)?youtube.com)?/(v/|watch\?v\=)([-|~_0-9A-Za-z]+)&?.*?#i',
'<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/$4?rel=0" frameborder="0" allowfullscreen></iframe>',
$string
);
}
$posted = youtube($posted);
$rexProtocol = '(https?://)?';
$rexDomain = '((?:[-a-zA-Z0-9]{1,63}\.)+[-a-zA-Z0-9]{2,63}|(?:[0-9]{1,3}\.){3}[0-9]{1,3})';
$rexPort = '(:[0-9]{1,5})?';
$rexPath = '(/[!$-/0-9:;=#_\':;!a-zA-Z\x7f-\xff]*?)?';
$rexQuery = '(\?[!$-/0-9:;=#_\':;!a-zA-Z\x7f-\xff]+?)?';
$rexFragment = '(#[!$-/0-9:;=#_\':;!a-zA-Z\x7f-\xff]+?)?';
// Solution 1:
function callback($match)
{
// Prepend http:// if no protocol specified
$completeUrl = $match[1] ? $match[0] : "http://{$match[0]}";
return '<a href="' . $completeUrl . '">'
. $match[2] . $match[3] . $match[4] . '</a>';
}
$posted = preg_replace_callback("&\\b$rexProtocol$rexDomain$rexPort$rexPath$rexQuery$rexFragment(?=[?.!,;:\"]?(\s|$))&",
'callback', $posted);
A popular solution to this problem is to use placeholders. On your first pass you turn all YouTube links into a placeholder, for example:
{{youtube:VhqiT2nWCVU}}
After that you run your normal link converter. And at the end your run yet another regex to turn all your palceholders into youtube embeds.
I have a Wordpress blog and am trying to implement the foresight.js image script. In short, I need to target all post images, swap out the src, width, & height attributes with data-src, data-width, & data-height attributes. I then need to duplicate the image line and wrap it in <noscript> tags. This is the structure I'm trying to have Wordpress generate/create:
<img data-src="wordpress/image/url/pic.jpg" data-width="{get width of image with PHP & pass-in that value here} data-height="{get height of image with PHP and pass-in that value here}" class="fs-img">
<noscript>
<img src="wordpress/image/url/pic.jpg">
</noscript>
More info can be found at foresight.js' website.
I have searched the Wordpress codex and the best possible route I can find are to use filters (ie. 'get_image_tag' & 'image_tag') for modifying the html that Wordpress outputs for each image. I'm thinking that one of these options should work, or that I can do some pattern matching with regex (I know, not ideal), throw in a preg_replace and then inject this back into the_content filter.
I have tried some of these options but cannot get any to work. Could someone please offer some help?
'get_image_tag' attempt:
Found this particular one on the web, but it would need modified to fit my logic (see above structure)...can't make sense of what the preg_replace array is doing on my own.
<?php function image_tag($html, $id, $alt, $title) {
return preg_replace(array(
'/'.str_replace('//','\/\/',get_bloginfo('url')).'/i',
'/\s+width="\d+"/i',
'/\s+height="\d+"/i',
'/alt=""/i'
),
array(
'',
'',
'',
alt='"' . $title . '"'
),
$html);
}
add_filter('get_image_tag', 'image_tag', 0, 4);
?>
Another 'get_image_tag' attempt:
<?php function get_image_tag($id, $alt, $title, $align, $size='full') {
list($width, $height, $type, $attr) = getimagesize($img_src);
$hwstring = image_hwstring($width, $height);
$class = 'align' . esc_attr($align) . ' size-' . esc_attr($size) . ' wp-image-' . $id;
$class = apply_filters('get_image_tag_class', $class, $id, $align, $size);
$html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" title="' . esc_attr($title).'" data-width="' . $width . '" data-height="' . $height . '" class="' . $class . ' fs-img" />';
$html = apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size);
return $html;
}
?>
Pattern-matching attempt:
Tried creating my own regex on this one, but not sure if it's correct.
<?php function restructure_imgs($content) {
global $post;
$pattern = "/<img(.*?)src=('|\")(.*?).(bmp|gif|jpeg|jpg|png)(|\")(.*?)>/i";
list($width, $height, $type, $attr) = getimagesize($2$3.$4$5);
$hwstring = image_hwstring($width, $height);
$replacement = '<img$1data-src=$2$3.$4$5 title="'.$post->post_title.'" data-width="'.$width.'" data-height="'.$height.'" class="fs-img"$6>';
$content = preg_replace($pattern, $replacement, $content);
return $content;
}
add_filter('the_content', 'restructure_imgs');
?>
Unfortunately can't get any of these examples to work. Any help or sharing your pre-written scripts/functions would be much appreciated! Thanks for helping a student learn!!
Your approach is before the page rendering and i think is not impossible in wordpress, however you can do the same after the page was rendered with javascript.
I tried to do that with jQuery and ti seems to work:
<!-- Example image -->
<img src="http://fotografia.deagostinipassion.com/resources/photos/2/2n/ilCielo.JPG" width="200px" height="300px">
<!-- Import jquery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$("img").wrap(function() {
$(this).wrap(function() {
var newimg = '<img data-src="' + $(this).attr('src') + '" data-width="' + $(this).attr('width') + '" data-height="' + $(this).attr('height') + '" class="fs-img">';
return newimg;
});
return '<noscript>';
});
});
</script>
If you need more help, ask me.
<?php
$i = 0;
$page = get_the_content();
$doc=new DOMDocument();
$doc->loadHTML($page);
$xml=simplexml_import_dom($doc);
$images=$xml->xpath('//img');
foreach ($images as $img) {
list($width, $height, $type, $attr) = getimagesize($img['src']);
if ($height > 149 ) {
echo '<img src="' . $img['src'] . '" alt=" ' . $img['alt'] . ' - funny and hot pictures" title=" ' . $img['title'] . ' - funny fail picture dump" onerror=\'this.style.display="none" \'><br>';
$i++;
if ($i == 3 ) { break;}
}
else
{
// don't display
}
}
?>
I replaced the "<?php the_content(); ?>" piece of code with the one above. It's supposed to strip out all of the text in my post and just leave the images which it does nicely. But when I embed a video the php breaks. How would I allow posts to show youtube videos?
You should look into using custom fields:
http://codex.wordpress.org/Custom_Fields
There is a great plugin that creates good admin control panels for them too:
http://wordpress.org/extend/plugins/advanced-custom-fields/
You could use a custom field to specifically put a video into the page.
Is there a particular reason you want to strip the text out of the post? - e.g. could you just not put text in the post at all? - or could the text be put into the excerpt instead, or into a custom field so that you don't have to over complicate the output code?