Skip to content

Instantly share code, notes, and snippets.

@kostiantyn-petlia
Last active October 25, 2019 08:57
Show Gist options
  • Save kostiantyn-petlia/462355b93f9a3500262996cd5ad58659 to your computer and use it in GitHub Desktop.
Save kostiantyn-petlia/462355b93f9a3500262996cd5ad58659 to your computer and use it in GitHub Desktop.
Youtube embed video URL with parameters or video ID from a common URL
/**
* Returns a Youtube video ID from URL
*
* @link https://regex101.com/
*
* @param string $url - target URL, like 'https://www.youtube.com/watch?v=C0DPdy98e4c' and similar
*
* @return bool|string - Youtube video ID, like 'C0DPdy98e4c', or false if no matches
*
* @author K
* @author 1.00
*
*/
function get_youtube_video_id( $url ) {
if ( empty( $url ) ) {
return false;
}
$reg_exp = '/(?:https?:\/\/)?(?:www\.)?youtu\.?be(?:\.com)?\/?.*(?:watch|embed)?(?:.*v=|v\/|\/)([\w\-_]+)\&?/';
preg_match( $reg_exp, $url, $matches );
if ( $matches && strlen( $matches[1] ) == 11 ) {
return $matches[1];
}
return false;
}
/**
* Returns a Youtube video embed URL from a common URL or a video ID
*
* @param string $target - the video URL or ID
* @param string|array $args - parameters of the embed link
* @param bool $target_is_id - true if $target is a video ID, instead a video URL
*
* @return bool|mixed|string - the embed youtube video link or false if fail
*
* @author K
* @author 1.01
*
*/
function get_youtube_embed_url( $target, $args = null, $target_is_id = false ) {
// Wrong parameters
if ( empty( $target ) || ( $target_is_id && strlen( $target ) != 11 ) ) {
return false;
} elseif ( ! ( $video_id = ( $target_is_id ) ? $target : get_youtube_video_id( $target ) ) ) {
return false;
}
// Init embed URL and string of parameters
$embed_url = 'https://www.youtube.com/embed/' . $video_id;
$args_string = '';
if ( ! empty( $args ) && is_string( $args ) && $args[0] == '?' && strlen( $args ) > 5 ) {
// The parameters are set as a string like '?autoplay=1&showinfo=1&rel=0'
$args_string = $args;
} else if ( ! empty( $args ) && is_array( $args ) ) {
// The parameters are set as an associative array
// Look at: https://developers.google.com/youtube/player_parameters
$allowed_params = array(
'autoplay',
'cc_load_policy',
'color',
'controls',
'disablekb',
'enablejsapi',
'end',
'fs',
'hl',
'iv_load_policy',
'list',
'listType',
'loop',
'modestbranding',
'origin',
'playlist',
'playsinline',
'rel',
'showinfo',
'start',
'widget_referrer',
'version',
'vq'
);
// Build a params string
foreach ( $args as $key => $arg ) {
if ( $arg != null && in_array( $key, $allowed_params ) ) {
$args_string .= "&{$key}={$arg}";
}
}
// The first chat must be '?'
if ( ! empty( $args_string ) && strlen( $args_string ) > 5 ) {
$args_string[0] = '?';
} else {
$args_string = '';
}
}
return esc_url( $embed_url . $args_string );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment