Posts Tagged ‘code’

YouTube shortcode fix for a blog imported from WordPress.com

November 27th, 2011

I recently moved a client from WordPress.com to a self-hosted WordPress installation. After I imported all her entries, I noticed that the shortcode WordPress.com had used to display her YouTube videos was no longer working. Instead, the shortcode itself was appearing, like this:

[youtube=http://www.youtube.com/watch?v=1LLls4hPEfM&w=500&h=311]

This is actually pretty easy to fix once your figure out the regular expression that can grab the YouTube video id, width and height from the shortcode. Then you add a shortcode definition to the functions.php file of your theme by copying and pasting this code:

function youtubeSC($atts) {
	$posttext = substr($atts[0],1);
	preg_match('/v\=([a-zA-Z0-9]+)/', $posttext, $youtubeID);
	preg_match('/w\=([0-9]+)/', $posttext, $width);
	preg_match('/h\=([0-9]+)/', $posttext, $height);
	
	return '<iframe width="' . $width[1] . '" height="' . $height[1] . '" src="http://www.youtube.com/embed/' . $youtubeID[1] . '" frameborder="0" allowfullscreen></iframe>';
}

Hope that helps!