How to change the way wp_embed handles only youtube videos?

What i’m trying to do is have youtube videos show a div when they stop playing. WordPress replaces youtube links automatically with embed code. Instead I’d like to replace it with something like:

function custom_ytube_embed ($content) {
    if (strstr($content,'http://www.youtube.com/embed/')) // see if any youtube embeds available
    {
        $pattern = "/version=3&rel=1&(.*?)&wmode=transparent'/s"; //param pattern
        $count = preg_match_all($pattern, $content, $matches); //find pattern and count matches

        foreach ($matches[0] as $match) {
        // replace matched params with new params

            if (is_single()) { //autoplay only on single pages
            $new_param = "autoplay=1&enablejsapi=1&modestbranding=1&rel=0&showinfo=0&iv_load_policy=3&wmode=transparent' id='vidID" . $count . "'";
        }
        else { //all other pages no auto play
            $new_param = "autoplay=0&enablejsapi=1&modestbranding=1&rel=0&showinfo=0&iv_load_policy=3&wmode=transparent' id='vidID" . $count . "'";
        }

        //replace params iframe with new params
        $content = str_replace($match, $new_param, $content);
        $count--;
    }
    return $content; 
    } 
    else {
        return $content; // if not found return it anyway
    }
}

function div_wrapper($content) {
    // match any iframes
    $pattern = '~<iframe.*</iframe>|<embed.*</embed>~';
    preg_match_all($pattern, $content, $matches);

    foreach ($matches[0] as $match) {
        // wrap matched iframe with div
        $wrappedframe = '<div class="video-container">' . $match . '</div>';

        //replace original iframe with new in content
        $content = str_replace($match, $wrappedframe, $content);
    }

    return $content;    
}

add_filter('the_content', 'custom_ytube_embed');
add_filter('the_content', 'div_wrapper');

This way i could rely on the youtube api to make the player and i can call a funtion when the player is done playing.
Also I need to pull the video id from the post as well. At first I tried remove_filter from the_content of the wpembed all together and then using add_filter to the_content to strip the original post of the youtube link and replace it but that isn’t ideal if someone was to post something besides a youtube video and my results didn’t go as well as I expected. I know my approach probably isn’t ideal as I don’t have much experience with wordpress. Any help is gladly appreciated.

Related posts