Embed YouTube or Vimeo Video From Video URL
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