Skip to content

Instantly share code, notes, and snippets.

@coreyweb
Created March 6, 2012 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save coreyweb/1982521 to your computer and use it in GitHub Desktop.
Save coreyweb/1982521 to your computer and use it in GitHub Desktop.
Youtube shortcode for WordPress
/**
* Youtube Shortcode Solution
*
* Set your desired width for all the videos on your site (below)
* Paste any Youtube video link in the shortcode, using this format, i.e.:
* [youtube value="http://www.youtube.com/watch?feature=player_embedded&v=GGT8ZCTBoBA"]
* This code will automatically resize your video to the appropriate size and aspect ratio.
* Modify the width value (set to 590 here), and the iframe code below to your desired settings.
* This requires coreylib (coreylib.com)
* Shortcode by coreyweb: https://github.com/coreyweb
* and collegeman: https://github.com/collegeman
*/
function youtube($atts) {
extract(shortcode_atts(array(
"value" => 'http://',
"width" => '590'
), $atts));
if (preg_match('#vi/(.*)/#i', $value, $matches)) {
$id = $matches[1];
} else if (preg_match('#v=([^&]+)#i', $value, $matches)) {
$id = $matches[1];
} else if (!parse_url($value, PHP_URL_HOST)) {
$id = $value;
} else {
return '<a href="'.$value.'">'.$value.'</a>';
}
$url = 'http://www.youtube.com/watch?v='.urlencode($id);
if ($oembed = coreylib('http://www.youtube.com/oembed?url='.$url.'&format=xml','1 month')) {
$newHeight = round($width * (string) $oembed->get('height') / (string) $oembed->get('width'));
return '<iframe width="'.$width.'" height="'.$newHeight.'" src="http://www.youtube.com/embed/'.$id.'?rel=0&amp;wmode=transparent" frameborder="0" allowfullscreen></iframe>';
} else {
return "Couldn't access oEmbed data for ".$url;
}
}
add_shortcode("youtube", "youtube");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment