WordPress auto embed of YouTube videos – adding filter to handle `end` attribute

WordPress automatically converts a YouTube URL in the content of a page/post to a embedded iframe video.

It respects the start parameter, if present, in the YouTube URL, but it does not respect the end parameter, if present.

Read More

I therefore need to locate the WordPress code that handles this automatic YouTube embed functionality so I can, hopefully, hook in my own filter that (using this solution) will take care of the end requirements.

I have searched through the class-wp-embed.php, class-oembed.php and media.php files of the /wp-includes/ directory and, in the latter, thought I had found the code I needed…

apply_filters( 'wp_embed_handler_youtube', $embed, $attr, $url, $rawattr )

…but that filter doesn’t seem to get called.

Can anyone point me in the right direction?

Related posts

2 comments

  1. I had same problems and not found answer. So here is working solution:

    add_filter('embed_oembed_html', 'my_theme_embed_handler_oembed_youtube', 10, 4);
    function my_theme_embed_handler_oembed_youtube($html, $url, $attr, $post_ID) {
        if (strpos($url, 'youtube.com')!==false) {
            /*  YOU CAN CHANGE RESULT HTML CODE HERE */
            $html = '<div class="youtube-wrap">'.$html.'</div>';
        }
        return $html;
    }
    
  2. You can customize the youtube url and set various condition.I have implemented it in past.You may get some reference from the below code:

     if(strpos($url, "youtube")!==false)
      {
        if(strpos($url, "<object")===false)
        {
         if(strpos($url, "<iframe")===false)
         {
          if(strpos($url, "//youtu.be/")===false)
          {
           $url_string = parse_url($url, PHP_URL_QUERY);
           parse_str($url_string, $args);
           $videoId = isset($args['v']) ? $args['v'] : false;
    
          }
          else
          {
           $url_string = explode('/',$url);
           $videoId = $url_string[3];
          }
         }
         else
         {
          $pattern = '!//(?:www.)?youtube.com/embed/([A-Za-z0-9-_]+)!i';
          $result = preg_match($pattern, $url, $matches);   
    
          $videoId = $matches[1];         
         }
        }
        else
        {
          preg_match('#<object[^>]+>.+?http://www.youtube.com/v/([A-Za-z0-9-_]+).+?</object>#s', $url, $matches);
          $videoId = $matches[1];
        }
        $urlfrom = 'youtube';
        $video_thumb= '';
    
    }
    

Comments are closed.