Extract Youtube and Vimeo ID from URL - functions.php
<div class="responsive-video aspect-16by9">
<?php
$video_url = get_post_meta( $post->ID, 'video_url', true );
if (strpos($video_url,'vimeo') == true): //vimeo video
?>
<iframe width="560" height="315" src="https://player.vimeo.com/video/<?php echo vimeo_id_from_url($video_url); ?>" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<?php
else: //vimeo video
?>
<iframe width="560" height="315" src="https://www.youtube.com/embed/<?php echo youtube_id_from_url($video_url); ?>" frameborder="0" allowfullscreen></iframe>
<?php endif; ?>
</div>
// extract youtube id from url
function youtube_id_from_url($url) {
$pattern =
'%^# Match any youtube URL
(?:https?://)? # Optional scheme. Either http or https
(?:www\.)? # Optional www subdomain
(?: # Group host alternatives
youtu\.be/ # Either youtu.be,
| youtube\.com # or youtube.com
(?: # Group path alternatives
/embed/ # Either /embed/
| /v/ # or /v/
| /watch\?v= # or /watch\?v=
) # End path alternatives.
) # End host alternatives.
([\w-]{10,12}) # Allow 10-12 for 11 char youtube id.
$%x';
$result = preg_match($pattern, $url, $matches);
if (false !== $result) {
return $matches[1];
}
return false;
}
//extract vimeo id from url
function vimeo_id_from_url($url) {
if (preg_match("/https?:\/\/(?:www\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^\/]*)\/videos\/|album\/(\d+)\/video\/|)(\d+)(?:$|\/|\?)/", $url, $id)){
$video_id = $id[3];
}
return $video_id;
}