Skip to content

Instantly share code, notes, and snippets.

@19h47
Last active May 2, 2023 08:07
Show Gist options
  • Save 19h47/f7c768f1541f191cddf993a68d334415 to your computer and use it in GitHub Desktop.
Save 19h47/f7c768f1541f191cddf993a68d334415 to your computer and use it in GitHub Desktop.
WP Get YouTube ID
<?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