WordPress: Create Your Own YouTube Embed Code

I have yet to find a good way of embedding YouTube videos in WordPress posts. If you copy the embed code YouTube provides, it’ll work unless you switch to the visual editor which mangles such code. If you look for a plugin to help you with the embedding, you’re in for an experience less pleasant than not using the visual editor.

A future version of WordPress promises to change this and give us mediatags to properly embed things. Until then, I would suggest you avoid the plugin repository entirely and use this little code snippet to write your own little shortcode tag to do the trick:

/**
 * YouTube Shortcodes
 */
add_shortcode('youtube', 'insertYouTube');
add_shortcode('yt', 'insertYouTube');

// Insert YouTube function
function insertYouTube($attr) {

	// defaults
	if (!$attr['width']) {
		$yt_w = 500;
	} else {
		$yt_w = $attr['width'];
	}
	if (!$attr['height']) {
		$yt_h = 400;
	} else {
		$yt_h = $attr['height'];
	}

	$yt .= '';

	// output YT
	if ($attr['src']) {
		$yt_id = str_replace( "=" , "" , $attr['src'] ) ;
		$yt_id = str_replace( "http://www.youtube.com/watch?v" , "" , $yt_id ) ;
		$yt_id = str_replace( "https://www.youtube.com/watch?v" , "" , $yt_id ) ;
		$yt_id = str_replace( "http://youtube.com/watch?v" , "" , $yt_id ) ;
		$yt_id = str_replace( "https://youtube.com/watch?v" , "" , $yt_id ) ;
		$yt_id = split('&', $yt_id);
		$yt_id = $yt_id[0];

	} else if ($attr[0]) {

		$yt_id = str_replace( "=" , "" , $attr[0] ) ;
		$yt_id = str_replace( "http://www.youtube.com/watch?v" , "" , $yt_id ) ;
		$yt_id = str_replace( "https://www.youtube.com/watch?v" , "" , $yt_id ) ;
		$yt_id = str_replace( "http://youtube.com/watch?v" , "" , $yt_id ) ;
		$yt_id = str_replace( "https://youtube.com/watch?v" , "" , $yt_id ) ;
		$yt_id = split('&', $yt_id);
		$yt_id = $yt_id[0];

	}

	// output
	$yt .= '
    
      
      
      
      
      
      
        You need the Flash Player.
      
      
      
    
	';

	$yt .= '';
	return $yt;

}

Syntax:

[youtube src="" width="500" height="400"]

Dump the above in your themes functions.php file, or pluginify it. I’m releasing this code under a Creative Commons Attribution 3.0 Unported License.

2 thoughts on “WordPress: Create Your Own YouTube Embed Code”

  1. #Wordpress: Create Your Own YouTube Embed Code: http://noscope.com/?p=5450

  2. coda says:

    Exactly what I was looking for. That viper’s video tags plugin (seems like the only alternative) is so excessive. Thanks!

Comments are closed.