Skip to content

Instantly share code, notes, and snippets.

@collegeman
Forked from coreyweb/youtube-shortcode.php
Created March 6, 2012 17:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save collegeman/1987525 to your computer and use it in GitHub Desktop.
Save collegeman/1987525 to your computer and use it in GitHub Desktop.
Youtube shortcode for WordPress
<?php
/**
* 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 ($oembed = coreylib('http://www.youtube.com/oembed?url='.urlencode($value).'&format=xml','1 month')) {
if (preg_match('#vi/(.*)/#i', $oembed->get('thumbnail_url'), $matches)) {
$id = $matches[1];
} else if (preg_match('#v=(.*)&?#i', $oembed->get('thumbnail_url'), $matches)) {
$id = $matches[1];
} else {
return '<a href="'.$value.'">'.$value.'</a>';
}
$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>';
}
}
add_shortcode("youtube", "youtube");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment