| |
| <?php
|
|
|
| function set_youtube_thumbnail_as_featured_image($post_id) {
|
|
|
| if (get_post_type($post_id) !== 'video') {
|
| return;
|
| }
|
|
|
|
|
| if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
|
| return;
|
| }
|
|
|
|
|
| $youtube_url = get_post_meta($post_id, 'video_url', true);
|
|
|
| if (!$youtube_url) {
|
| return;
|
| }
|
|
|
|
|
| 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];
|
|
|
|
|
| $thumbnail_urls = [
|
| "https://img.youtube.com/vi/$video_id/maxresdefault.jpg",
|
| "https://img.youtube.com/vi/$video_id/sddefault.jpg",
|
| "https://img.youtube.com/vi/$video_id/hqdefault.jpg",
|
| "https://img.youtube.com/vi/$video_id/mqdefault.jpg"
|
| ];
|
|
|
| $thumbnail_url = null;
|
| foreach ($thumbnail_urls as $url) {
|
|
|
| $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 ($http_code === 200) {
|
| $thumbnail_url = $url;
|
| break;
|
| }
|
| }
|
|
|
| if ($thumbnail_url) {
|
|
|
| $image_data = file_get_contents($thumbnail_url);
|
|
|
| if ($image_data) {
|
|
|
| $upload_dir = wp_upload_dir();
|
|
|
|
|
| $image_path = $upload_dir['path'] . '/' . $video_id . '.jpg';
|
|
|
|
|
| file_put_contents($image_path, $image_data);
|
|
|
|
|
| $filetype = wp_check_filetype($image_path, null);
|
|
|
|
|
| $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',
|
| );
|
|
|
|
|
| $attach_id = wp_insert_attachment($attachment, $image_path, $post_id);
|
|
|
|
|
| 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_post_thumbnail($post_id, $attach_id);
|
| }
|
| }
|
| }
|
| }
|
|
|
|
|
| add_action('save_post', 'set_youtube_thumbnail_as_featured_image');
|
|
|
| |
| |
Comments