ID ) ) { return; } // Get the post content and search for a YouTube URL $content = $post->post_content; preg_match_all('~(https?://www\.youtube\.com/watch\?v=)([a-zA-Z0-9_-]+)~', $content, $matches); if ( empty($matches[2]) ) { return; } $videoId = $matches[2][0]; $youtubeImageSrc = "https://img.youtube.com/vi/$videoId/"; // Determine the best available thumbnail size $possibleThumbnails = ['maxresdefault.jpg', 'hqdefault.jpg', 'mqdefault.jpg']; $youtubeImage = ''; foreach ($possibleThumbnails as $thumbnail) { $headers = get_headers($youtubeImageSrc . $thumbnail, 1); if ($headers && strpos($headers[0], '200 OK') !== false) { $youtubeImage = $thumbnail; break; } } if (!$youtubeImage) { error_log('No valid YouTube thumbnail found.'); return; } $thumbnailUrl = $youtubeImageSrc . $youtubeImage; // Fetch the image $response = wp_safe_remote_get($thumbnailUrl); if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) { error_log('Error fetching the thumbnail: ' . $response->get_error_message()); return; } $imageData = wp_remote_retrieve_body($response); if (empty($imageData)) { error_log('Failed to retrieve image data.'); return; } // Get image dimensions list($width, $height) = getimagesizefromstring($imageData); // Prepare the file for upload $uploadDir = wp_upload_dir(); $filename = wp_unique_filename($uploadDir['path'], 'youtube-thumbnail-' . $post->ID . '.webp'); $filePath = $uploadDir['path'] . '/' . $filename; // Create an image resource and save it as WebP $image = imagecreatefromstring($imageData); if (!$image) { error_log('Failed to create image resource.'); return; } if (!imagewebp($image, $filePath)) { error_log('Failed to save the image as WebP.'); imagedestroy($image); return; } imagedestroy($image); // Create an attachment for the image $attachment = array( 'post_mime_type' => 'image/webp', 'guid' => $uploadDir['url'] . '/' . $filename, 'post_parent' => $post->ID, 'post_title' => 'YouTube Thumbnail', 'post_content' => '', 'post_status' => 'inherit' ); $attachmentId = wp_insert_attachment($attachment, $filePath); // Set the thumbnail as the featured image and update meta information if (!is_wp_error($attachmentId)) { set_post_thumbnail($post->ID, $attachmentId); update_post_meta($attachmentId, '_wp_attachment_image_alt', get_the_title()); } else { error_log('Error creating attachment: ' . $attachmentId->get_error_message()); } } add_action('save_post', 'generate_youtube_thumbnail');