Last active
May 2, 2023 08:07
-
-
Save 19h47/f7c768f1541f191cddf993a68d334415 to your computer and use it in GitHub Desktop.
WP Get YouTube ID
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 | |
/** | |
* Plugin Name: WP Get YouTube ID | |
* Plugin URI: https://gist.github.com/19h47/f7c768f1541f191cddf993a68d334415 | |
* Description: WordPress insert image. | |
* Version: 0.0.0 | |
* Author: Jérémy Levron | |
* Author URI: https://19h47.fr | |
*/ | |
if ( ! function_exists( 'get_youtube_id_from_url' ) ) { | |
/** | |
* Get YouTube ID from URL. | |
* | |
* @see https://gist.github.com/MarioRicalde/1163103 | |
* | |
* @param string $url YouTube URL. | |
*/ | |
function get_youtube_id_from_url( string $url ) : string { | |
// Regular Expression (the magic). | |
$regexp = '/^https?:\/\/(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?(?=.*v=([\w\-]+))(?:\S+)?|([\w\-]+))$/i'; | |
// Match a URL. | |
preg_match( $regexp, $url, $matches ); | |
// Remove empty values from the array (regexp shit). | |
$matches = array_filter( | |
$matches, | |
function( $var ) { | |
return '' !== $var; | |
} | |
); | |
// If we have 2 elements in array, it means we got a valid url! | |
// $matches[1] is the youtube ID! | |
if ( count( $matches ) === 2 ) { | |
return $matches[1]; | |
} | |
return ''; | |
} | |
} | |
if ( ! function_exists( 'get_youtube_id_from_iframe' ) ) { | |
/** | |
* Get YouTube Id from iframe. | |
* | |
* @param string $iframe iframe YouTube | |
* | |
* @see https://stackoverflow.com/a/41544603/5091221 | |
* | |
* @return string | |
*/ | |
function get_youtube_id_from_iframe( string $iframe ) : string { | |
if ( ! is_string( $iframe ) ) { | |
return ''; | |
} | |
// Extract video url from embed code. | |
return preg_replace_callback( | |
'/<iframe\s+.*?\s+src=(".*?").*?<\/iframe>/', | |
function ( $matches ) { | |
$url = $matches[1]; | |
$url = trim( $url, '"' ); | |
$url = trim( $url, "'" ); | |
preg_match( "/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'>]+)/", $url, $video_id ); | |
return isset( $video_id[1] ) ? $video_id[1] : ''; | |
}, | |
$iframe | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment