Wordpress | 280 Views

How to Embed YouTube and Vimeo Videos with a Single PHP Function

's Gravatar
Oct 1, 2023

Want to simplify video embedding on your website? Whether it’s a YouTube or Vimeo video, this guide shows you how to create one PHP function to handle both — with support for autoplay, mute, loop, and more.

This method is perfect for developers looking to build dynamic, customizable websites without repetitive code.

Why Use a Single Function?

Most websites use both YouTube and Vimeo for content delivery. Instead of manually adjusting embed codes, you can:

  • Streamline your embed logic
  • Enable video options like autoplay or mute dynamically
  • Maintain consistency across your site

To create a single function that can handle both YouTube and Vimeo video URLs and generate an embedded video player code, you can follow these steps. We’ll use PHP for this example.

Here’s a function called customize_embedded_video that takes a video URL as input and returns the embedded player code:

 

<?php // Register a new handler for custom video sources
function customize_embedded_video($video_type, $embed_media, $autoplay = null, $loop = null, $muted = null) {
    if($autoplay != null){
        $autoplay_value = 1;
    }
    if($loop != null){
        $loop_value = 1;
    }
    if($muted != null){
        $muted_value = 1;
    }
    
    if ($video_type == 'embed') {
        // Use preg_match to find iframe src.
        preg_match('/src="(.+?)"/', $embed_media, $matches);
        $queryString = parse_url($embed_media, PHP_URL_QUERY);
		
        // Parse the query string and get the value of 'v' parameter
        parse_str($queryString, $params);

        $src = $matches[1];

        // Check if the iframe contains a YouTube URL.
        if (strpos($src, 'youtube.com') !== false) {
            // Add extra parameters to src.
			
			$videoId = extractYouTubeVideoId($src);
            $params = array(
                'autoplay' => $autoplay_value,
                'mute' => $muted_value,
                'autohide' => 1,
                'modestbranding' => 1,
                'rel' => 0, 
                'showinfo' => 0, 
                'controls' => 0,
                'disablekb' => 1, 
                'enablejsapi' =>  1, 
                'iv_load_policy'=> 3,
                'loop' => $loop_value,
                'cc_load_policy' => 1,
                'vq' => 'hd720',
		'playlist' => $videoId,
            );
        }
        // Check if the iframe contains a Vimeo URL.
        elseif (strpos($src, 'vimeo.com') !== false) {
            // Add extra parameters to src.
            $params = array(
                'autoplay' => $autoplay_value,
                'loop' => $loop_value,
                'autopause' => 0,
                'background' => 1,
                'muted' => $muted_value,
            );
        }

        // Add extra parameters to src and replace HTML.
        $new_src = add_query_arg($params, $src);
        $embed_media = str_replace($src, $new_src, $embed_media);

        // Add extra attributes to iframe HTML.
        $attributes = 'frameborder="0"';
        $embed_media = str_replace('></iframe>', ' ' . $attributes . ' style="pointer-events: none"></iframe>', $embed_media);

        return $embed_media;
    }

    return ''; // Return empty string if $video_type is not 'embed'
} ?>

To Support this write another function

<?php function extractYouTubeVideoId($url) {
    // Use preg_match to find the video ID for both formats
    preg_match('/[?&]v=([a-zA-Z0-9_-]+)/', $url, $matches);

    if (isset($matches[1])) {
        $videoId = $matches[1];
        return $videoId;
    } else {
        // If the video ID is not found using the first pattern, try the second pattern
        preg_match('/\/([a-zA-Z0-9_-]+)(\?|$)/', $url, $matches);

        if (isset($matches[1])) {
            $videoId = $matches[1];
            return $videoId;
        }
    }
} ?>

In php files

<?php 
     $modified_embed_media = customize_embedded_video($video_type, $embed_media, $autoplay, $loop , $muted);
     echo $modified_embed_media; 

?>

Supported Url

https://www.youtube.com/watch?v=VIDEO_ID
https://youtube.com/watch?v=VIDEO_ID
https://youtube.com/watch?v=VIDEO_ID%3Ffeature%3Doembed
https://player.vimeo.com/video/90617432