Created
December 2, 2016 18:08
-
-
Save stephenbelyea/739c860e6c48161bd9447f942458be6d to your computer and use it in GitHub Desktop.
Format YouTube video link for embed without cross domain origin error.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if (get_field('video_link')) : | |
// Video_link is the field from WP's ACF (can be any URL string | |
// from YouTube), while embed_link will be the string we use. | |
$video_link = get_field('video_link'); | |
$embed_link = ""; | |
// Proper embed link, move along. | |
if ( strpos($video_link, '/embed/') !== false ) { | |
$embed_link = $video_link; | |
} | |
// Share link, will need to grab video ID. | |
elseif ( strpos($video_link, 'youtu.be/') !== false ) { | |
$video_link_array = explode('youtu.be/', $video_link); | |
$video_link_id = $video_link_array[1]; | |
if ( strpos($video_link_id, '&') !== false ) { | |
$video_link_params = explode('&', $video_link_array[1]); | |
$video_link_id = $video_link_params[0]; | |
} | |
$embed_link = 'https://www.youtube.com/embed/' . $video_link_id; | |
} | |
// Page URL, will need to grab video ID. | |
elseif ( strpos($video_link, '/watch?v=') !== false ) { | |
$video_link_array = explode('/watch?v=', $video_link); | |
$video_link_id = $video_link_array[1]; | |
if ( strpos($video_link_id, '&') !== false ) { | |
$video_link_params = explode('&', $video_link_array[1]); | |
$video_link_id = $video_link_params[0]; | |
} | |
$embed_link = 'https://www.youtube.com/embed/' . $video_link_id; | |
} | |
endif; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment