Created
May 3, 2022 12:10
-
-
Save rahulsprajapati/7fa0445fcaec08648d4a90e2abaf8c02 to your computer and use it in GitHub Desktop.
Get youtube video id from url.
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
<?php | |
/** | |
* Determine the video ID from the URL. | |
* | |
* @param string $url URL. | |
* | |
* @return int|false Video ID, or false if none could be retrieved. | |
*/ | |
function get_video_id_from_url( $url ) { | |
$parsed_url = wp_parse_url( $url ); | |
if ( ! isset( $parsed_url['host'] ) ) { | |
return false; | |
} | |
$domain = implode( '.', array_slice( explode( '.', $parsed_url['host'] ), -2 ) ); | |
if ( ! in_array( $domain, [ 'youtu.be', 'youtube.com', 'youtube-nocookie.com' ], true ) ) { | |
return false; | |
} | |
if ( ! isset( $parsed_url['path'] ) ) { | |
return false; | |
} | |
$segments = explode( '/', trim( $parsed_url['path'], '/' ) ); | |
$query_vars = []; | |
if ( isset( $parsed_url['query'] ) ) { | |
wp_parse_str( $parsed_url['query'], $query_vars ); | |
// Handle video ID in v query param, e.g. <https://www.youtube.com/watch?v=XOY3ZUO6P0k>. | |
// Support is also included for other query params which don't appear to be supported by YouTube anymore. | |
if ( isset( $query_vars['v'] ) ) { | |
return $query_vars['v']; | |
} elseif ( isset( $query_vars['vi'] ) ) { | |
return $query_vars['vi']; | |
} | |
} | |
if ( empty( $segments[0] ) ) { | |
return false; | |
} | |
// For shortened URLs like <http://youtu.be/XOY3ZUO6P0k>, the slug is the first path segment. | |
if ( 'youtu.be' === $parsed_url['host'] ) { | |
return $segments[0]; | |
} | |
// For non-shortened URLs, the video ID is in the second path segment. For example: | |
// * https://www.youtube.com/watch/XOY3ZUO6P0k | |
// * https://www.youtube.com/embed/XOY3ZUO6P0k | |
// Other top-level segments indicate non-video URLs. There are examples of URLs having segments including | |
// 'v', 'vi', and 'e' but these do not work anymore. In any case, they are added here for completeness. | |
if ( ! empty( $segments[1] ) && in_array( $segments[0], [ 'embed', 'watch', 'v', 'vi', 'e' ], true ) ) { | |
return $segments[1]; | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment