Here's the scenario, I have a site with thousands of YouTube video posts which are stored in a custom field 'video_url' which is being used in a custom video player.
The custom player I'm using now doesn't take the entire YouTube URL but instead just the video ID. What I need to do is figure out how to grab the YouTube video ID from the url in the custom field and place that into a HTML 5 video attribute.
<video class="custom-player" data-youtube-id="YOUTUBE_ID_HERE" width="700" height="420" preload="none"></video>
Thanks.
Update: Answer
Credits to Chandan Chaudhary https://gist.github.com/ckchaudhary/8629242#file-get-youtube-video-id-from-url
Add the following to the functions.php file.
function extractUTubeVidId($url){
/*
* type1: http://www.youtube.com/watch?v=9Jr6OtgiOIw
* type2: http://www.youtube.com/watch?v=9Jr6OtgiOIw&feature=related
* type3: http://youtu.be/9Jr6OtgiOIw
*/
$vid_id = "";
$flag = false;
if(isset($url) && !empty($url)){
/*case1 and 2*/
$parts = explode("?", $url);
if(isset($parts) && !empty($parts) && is_array($parts) && count($parts)>1){
$params = explode("&", $parts[1]);
if(isset($params) && !empty($params) && is_array($params)){
foreach($params as $param){
$kv = explode("=", $param);
if(isset($kv) && !empty($kv) && is_array($kv) && count($kv)>1){
if($kv[0]=='v'){
$vid_id = $kv[1];
$flag = true;
break;
}
}
}
}
}
/*case 3*/
if(!$flag){
$needle = "youtu.be/";
$pos = null;
$pos = strpos($url, $needle);
if ($pos !== false) {
$start = $pos + strlen($needle);
$vid_id = substr($url, $start, 11);
$flag = true;
}
}
}
return $vid_id;
}
The add this to the post loop.
<?php
$videoID = get_post_meta($post->ID, 'video_url', true);
echo $youtube_video_id = extractUTubeVidId($videoID);
?>
Change 'video_url' to whatever custom field name your YouTube video URLs are stored in.
parse_url()
as it may lend itself to a slightly better solution.