Get the YouTube or Vimeo video ID from a URL
Many users think that websites without media (audio, video, etc.) are pretty boring. I really hope that does not apply to HelloAdmin 😁 That is why the vast majority of sites have media content. As a rule, videos are not stored on the site itself but on a video hosting like YouTube or Vimeo: it promotes the channel and, of course, saves disk space.
Take YouTube: every video has a unique ID, but the URL formats are different: https://www.youtube.com/watch?v=ID, https://youtube.com/?v=ID, https://youtu.be/ID, https://www.youtube.com/embed/ID. To get the ID we need a regular expression.
Problem: An editor pastes any YouTube or Vimeo link into a field, and the site has to show the video player.
Solution: Get the video ID from the URL and build the embed URL of the player. Add to functions.php:
<?php
function get_video_embed_url( $video_url ) {
// Vimeo: https://vimeo.com/123456789 or https://player.vimeo.com/video/123456789
if ( false !== strpos( $video_url, 'vimeo.com' ) && preg_match( '~vimeo\.com/(?:.*/)?(\d+)~', $video_url, $m ) ) {
return 'https://player.vimeo.com/video/' . $m[1];
}
// YouTube: watch?v=, youtu.be/, embed/, v/, shorts/
if ( preg_match( "~^(?:https?://)?(?:www\.|m\.)?(?:youtu\.be/|youtube\.com/(?:(?:watch)?\?(?:.*&)?vi?=|(?:embed|v|vi|shorts)/))([\w-]{11})~", $video_url, $m ) ) {
return 'https://www.youtube.com/embed/' . $m[1];
}
return false;
}
function display_youtube_or_vimeo_video( $video_url ) {
$embed_url = get_video_embed_url( $video_url );
if ( $embed_url ) {
echo '<iframe src="' . esc_url( $embed_url ) . '" title="Video player" loading="lazy" frameborder="0" '
. 'allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
}
}
Usage, for example with an ACF URL field:
<?php display_youtube_or_vimeo_video( get_field( 'video_url' ) );
A YouTube ID is always 11 characters (letters, digits, - and _), so the expression takes exactly 11 and ignores the rest of the URL, such as &t=30s or ?feature=share. A Vimeo ID is a number.
NOTE: If you only need the player and not the ID itself, WordPress can do it without regular expressions: echo wp_oembed_get( $video_url ); returns the embed code for YouTube, Vimeo and other services it supports. The ID is still useful when you need your own markup, a preview image (https://img.youtube.com/vi/ID/hqdefault.jpg) or player parameters.
Sources: