Skip links

WordPress save youtube or vimeo thumbnail as featured image

How to save youtube or vimeo thumbnail as featured image of wordpress post.For a examaple if you add the video url as custom meta data or post content you need to get it’s video thumbnail and save it as featured image automatically.
This post is discussing how to save youtube vimeo thumbnail as featured image in wordpress post or page or custom post types.

Wordpress save youtube or vimeo thumbnail as featured image
Copy and paste the following function and hook into theme function.php file and save it. Featured image will save when post is save.

function sh_set_youtube_as_featured_image( $post_id ) { 
    // only want to do this if the post has no thumbnail 
    if(!has_post_thumbnail($post_id)) { 
        // find the youtube url from post contents 
        $post_array = get_post($post_id, ARRAY_A); 
        $content = $post_array['post_content']; 
        //$youtube_id = get_youtube_id($content); 
        $videoURL = get_post_meta($post_id,'video_link','true'); 
        
        // CUSTOM META BOX I HAVE ADDED. 
        $type = sh_videoType($videoURL); 
        if($type=='youtube') { 
            preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $videoURL, $matches); 
            $youtube_id = $matches[0]; 
            
            // build the thumbnail string 
            $youtube_thumb_url = 'http://img.youtube.com/vi/' . $youtube_id . '/0.jpg'; 
            
            // next, download the URL of the youtube image 
            media_sideload_image($youtube_thumb_url, $post_id, 'Video thumbnail.'); 
        } if($type=='vimeo') { 
            preg_match("/(https?:\/\/)?(www\.)?(player\.)?vimeo\.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*/", $videoURL, $matchesx); 
            $vimeo_id = $matchesx[5]; 
            $imagex   = unserialize(file_get_contents("http://vimeo.com/api/v2/video/$vimeo_id.php")); $vimeo_thumb_url = $imagex[0]['thumbnail_large']; 
            media_sideload_image($vimeo_thumb_url, $post_id, 'Video thumbnail.'); 
        } 
        // find the most recent attachment for the given post 
        $attachments = get_posts( array( 'post_type' => 'attachment', 'numberposts' => 1, 'order' => 'ASC', 'post_parent' => $post_id ) ); 
        $attachment = $attachments[0]; 
        
        // and set it as the post thumbnail 
        set_post_thumbnail( $post_id, $attachment->ID ); 
    } // end if 
} 

// set_youtube_as_featured_image 
add_action('save_post', 'sh_set_youtube_as_featured_image'); 

// return video type 
function sh_videoType($url) { 
    if (strpos($url, 'youtube') > 0) { 
        return 'youtube'; 
    } elseif (strpos($url, 'vimeo') > 0) { 
        return 'vimeo'; 
    } else { 
        return 'unknown'; 
    } 
}

 

That’s only. Leave a comment here if you have problem or your ideas.
Thank you