Skip to content

Instantly share code, notes, and snippets.

@stephenbelyea
Created December 2, 2016 18:08
Show Gist options
  • Save stephenbelyea/739c860e6c48161bd9447f942458be6d to your computer and use it in GitHub Desktop.
Save stephenbelyea/739c860e6c48161bd9447f942458be6d to your computer and use it in GitHub Desktop.
Format YouTube video link for embed without cross domain origin error.
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