Created
March 6, 2012 00:45
-
-
Save coreyweb/1982521 to your computer and use it in GitHub Desktop.
Youtube shortcode for WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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&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