Home / Widgets / Use YouTube Thumbnail as Featured Image
Duplicate Snippet

Embed Snippet on Your Site

Use YouTube Thumbnail as Featured Image

Code Preview
php
<?php
// Hook into the save_post action to set the YouTube thumbnail as the featured image
function set_youtube_thumbnail_as_featured_image($post_id) {
    // Check if the post type is 'video' to avoid running on other post types
    if (get_post_type($post_id) !== 'video') {
        return;
    }
    // Avoid infinite loop when updating the post
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    // Get the YouTube video URL (from the custom field 'video_url')
    $youtube_url = get_post_meta($post_id, 'video_url', true);
    if (!$youtube_url) {
        return;
    }
    // Extract the video ID from the YouTube URL
    preg_match('/(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/', $youtube_url, $matches);
    if (isset($matches[1])) {
        $video_id = $matches[1];
        // Check availability of thumbnails
        $thumbnail_urls = [
            "https://img.youtube.com/vi/$video_id/maxresdefault.jpg", // Max-res thumbnail
            "https://img.youtube.com/vi/$video_id/sddefault.jpg",    // Standard definition
            "https://img.youtube.com/vi/$video_id/hqdefault.jpg",    // High quality
            "https://img.youtube.com/vi/$video_id/mqdefault.jpg"     // Medium/normal quality
        ];
        $thumbnail_url = null;
        foreach ($thumbnail_urls as $url) {
            // Use cURL to check if the thumbnail exists
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_NOBODY, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 5);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            // If the thumbnail is found (HTTP 200), use this URL
            if ($http_code === 200) {
                $thumbnail_url = $url;
                break;
            }
        }
        if ($thumbnail_url) {
            // Download the image
            $image_data = file_get_contents($thumbnail_url);
            if ($image_data) {
                // Get the upload directory path
                $upload_dir = wp_upload_dir();
                // Define the path for the new image
                $image_path = $upload_dir['path'] . '/' . $video_id . '.jpg';
                // Save the image to the server
                file_put_contents($image_path, $image_data);
                // Check the file type
                $filetype = wp_check_filetype($image_path, null);
                // Prepare attachment data
                $attachment = array(
                    'guid' => $upload_dir['url'] . '/' . basename($image_path),
                    'post_mime_type' => $filetype['type'],
                    'post_title' => sanitize_file_name(basename($image_path)),
                    'post_content' => '',
                    'post_status' => 'inherit',
                );
                // Insert the attachment into the media library
                $attach_id = wp_insert_attachment($attachment, $image_path, $post_id);
                // Generate metadata for the attachment
                require_once(ABSPATH . 'wp-admin/includes/image.php');
                $attach_data = wp_generate_attachment_metadata($attach_id, $image_path);
                wp_update_attachment_metadata($attach_id, $attach_data);
                // Set the post thumbnail
                set_post_thumbnail($post_id, $attach_id);
            }
        }
    }
}
// Add the function to the 'save_post' hook
add_action('save_post', 'set_youtube_thumbnail_as_featured_image');

Comments

Add a Comment