Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Replace the Youtube embed with a thumbnail
<?php
add_filter( 'oembed_result', 'fwe_oembed_result', 10, 3 );
function fwe_oembed_result( $result, $url, $args ){
//Uebernommen aus wp-includes/class-oembed.php
//L38ff
$youtube_regex = array(
'#http://((m|www)\.)?youtube\.com/watch.*#i',
'#https://((m|www)\.)?youtube\.com/watch.*#i',
'#http://youtu\.be/.*#i',
'#https://youtu\.be/.*#i',
);
$is_youtube = false;
foreach( $youtube_regex as $regex ){
if( preg_match( $regex, $url ) && ! $is_youtube ){
$is_youtube = true;
break;
}
}
//Wenn es kein Youtube-Link ist
if( ! $is_youtube )
return $result;
//RegEx fuer Youtube ID
//Quelle: http://stackoverflow.com/questions/2936467/parse-youtube-video-id-using-preg-match
$youtubeid_regex = '%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i';
if (! preg_match( $youtubeid_regex, $url, $match ) )
return $result;
$src = 'https://i.ytimg.com/vi/' . $match[1] . '/hqdefault.jpg';
$html = '<div class="youtube-wrapper" data-youtube="' . $match[1] . '"><img src="' . $src . '" alt="Youtube Thumbnail" /></div>';
return $html;
}
add_action( 'init', 'init_script' );
function init_script(){
wp_enqueue_script( 'youtube-thumbs', plugins_url( '/script.js', __FILE__ ), array( 'jquery' ) );
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment