Embed YouTube or Vimeo Video From Video URL


About The Author
Cabe Nolan is the founder of WP Cover where he shares his insight into WordPress, development, & entrepreneurship. Outside of WPCover, Cabe continues to run a successful WordPress development firm, Bold City Design as well as a few high profile websites, Arrivala, Two Way Resume, Dock Skipper, and a successful outdoors brand, DolfinPack.







Embed YouTube or Vimeo Video From Video URL

Recently I needed to write a function that would parse a Vimeo or YouTube video URL and enable me to embed the video into a WordPress theme.  Vimeo was pretty straight forward as their video links for the most part are pretty standard.  YouTube was a little more difficult as I tried to account for the different domains YouTube would use such as youtu.be.  As a finished product, here is the function I placed in my active WordPress themes function.php file:


function parseVideos($url) {
	//store the URL into a variable
	if (strpos($url, "youtu")) {
		// check for type of youtube link
		preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $url, $matches);
		 
		$id = $matches[0];
		return $id;
	} elseif (strpos($url, "vimeo.com")) {
		//extract the ID
		preg_match(
			'/\/\/(www\.)?vimeo.com\/(\d+)($|\/)/',
			$url,
			$matches
		);
	 
	$id = $matches[2];
	 
	 
	return $id;
 
	} else {
		return 'We could not parse your video. Please edit the URL';
	}
}

Once that was in place, I used something along the lines of the following to embed the video:


<?php $vidid = parseVideos( get_field('video_url') );
if($vidid !== 'We could not parse your video. Please edit the URL') { 
	if (strpos(get_field('video_url'), "youtu")) { ?>
		<iframe width="560" height="315" src="https://www.youtube.com/embed/<?php echo $vidid; ?>" frameborder="0" allowfullscreen></iframe>
	<?php } elseif(strpos(get_field('video_url'), "vimeo.com")) { ?>
		<iframe src="https://player.vimeo.com/video/<?php echo $vidid; ?>" width="640" height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
	<?php } else { ?>
		Nothing to show
	<?php } ?>
<?php } else { ?>
	<?php echo $vidid; ?>
<?php } ?>

And that’s your quick snippet of the day!  Hope this helps someone else who is looking to embed a YouTube or Vimeo video based on an inputted URL.


Share Your Thoughts

Leave a Reply

Your email address will not be published.


Related Stuff You Might Like







WordPress News, Tips, & Code Snippets

Join the WP Cover mailing list and get wordpress news, tips, code snippets, security warnings, and more delivered right to your inbox.  We won't flood your inbox, newsletters typically go out every 1-2 weeks unless it involves an important security release.

You have Successfully Subscribed!