Get YouTube or Vimeo video ID

Many users think websites without media (audio, videos, etc) are pretty boring. I really hope, that doesn’t apply to HelloAdmin 😁 That is why, vast majority sites contain media-content. As rule, video content doesn’t placed to self website but for that use video hosting such as YouTube, Vimeo, etc. This choice, dictated by need to promotion resource and of coгrse save hard disk space.

For example, let’s views YouTube case, where each video has unique ID, but URL’s format can be various: https://www.youtube.com/watch?v=ID, https://youtube.com/?v=ID, https://youtu.be/ID. In order get ID we need use regular expression.

Problem: How to correct display YouTube or Vimeo videos.

Solution: Add next code to functions.php:

<?php 

function display_youtube_or_vimeo_video( $video_url ) {
	if ( strpos( $video_url, 'vimeo.com' ) !== false ) {
		$video_id = preg_replace( '/[^\/]+[^0-9]|(\/)/', '', rtrim( $video_url, '/' ) );
		$video_url = 'https://player.vimeo.com/video/' . $video_id;
	} elseif ( strpos( $video_url, 'youtu.be' ) || strpos( $video_url, 'youtube' ) !== false ) {
		preg_match( "/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user|shorts)\/))([^\?&\"'>]+)/", $video_url, $matches );
		$video_url = 'https://www.youtube.com/embed/' . $matches[1];
	}
	
	$iframe = '<iframe src="' . $video_url . '" title="Video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
	echo $iframe;
}

NOTE: The regex covers the most common YouTube URL formats — youtube.com/watch?v=, youtu.be/, youtube.com/embed/, and Shorts — but short-lived or regional URL variants may not match. Always test against your actual video URLs before deploying to production.

Sources:

  1. https://stackoverflow.com/questions/3392993/php-regex-to-get-youtube-video-id
  2. https://stackoverflow.com/questions/10488943/easy-way-to-get-vimeo-id-from-a-vimeo-url