WordPress – thumbnail image from youtube (function and loop)

Well, assuming the post content will be provided by Youtube embedded code, a change in the regular expression is needed.

The function must obtain the source of the iframe. So would be as follows:

function get_thumbnail_fromyoutube( $size = 0 ) {
global $post, $posts;
$youtube="";
$get_url = preg_match_all('/src="https://wordpress.stackexchange.com/questions/151570/([^"]+)"https://wordpress.stackexchange.com/", $post->post_content, $matches);
$youtube = $matches[1][0];
var_dump($youtube);
if(preg_match('/^(http:\/\/www.youtube.com)/', $youtube)) {
    $youtube = preg_replace('/(.*?).embed\//', '', $youtube);
    $youtube = preg_replace('/\?.(.*?)$/', '', $youtube);
    echo '<img src="http://img.youtube.com/vi/' . $youtube . "https://wordpress.stackexchange.com/" . $size . '.jpg" alt="' . $post->post_title . '" />';
}

}

Where the variable “get_url” stores the URL of the video.

And always remember to remove the “img” tag inside the Loop, leaving only the conditional statement.

<?php if (has_post_thumbnail()) ? the_post_thumbnail('thumbnail') : get_thumbnail_fromyoutube(); ?>

Leave a Comment