Skip to content

Instantly share code, notes, and snippets.

@woraperth
Last active August 3, 2022 20:39
Show Gist options
  • Save woraperth/8c7d676e9fc37ef0c09107e90503258b to your computer and use it in GitHub Desktop.
Save woraperth/8c7d676e9fc37ef0c09107e90503258b to your computer and use it in GitHub Desktop.
[WordPress] Get Youtube video thumbnail from URL & Set as Featured Image
// Get Youtube URL
$yturl = 'https://www.youtube.com/watch?v=HhAKNSsb4t4';
preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'>]+)/", $yturl, $matches);
$video_id = $matches[1];
// Get Thumbnail
$file_headers = get_headers( 'http://img.youtube.com/vi/' . $video_id . '/maxresdefault.jpg' );
$is_404 = $file_headers[0] == 'HTTP/1.0 404 Not Found' || false !== strpos( $file_headers[0], '404 Not Found' );
$video_thumbnail_url = $is_404 ? 'http://img.youtube.com/vi/' . $youtube_id . '/maxresdefault.jpg' : 'http://img.youtube.com/vi/' . $video_id . '/hqdefault.jpg';
// required libraries for media_sideload_image
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
// $post_id == the post you want the image to be attached to
// $video_thumb_url == the vimeo video's thumb url
// $description == optional description
// load the image
$result = media_sideload_image($video_thumbnail_url, 1);
// then find the last image added to the post attachments
$attachments = get_posts(array('numberposts' => '1', 'post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC'));
if(sizeof($attachments) > 0){
// set image as the post thumbnail
set_post_thumbnail($post_id, $attachments[0]->ID);
}
@rongenius757
Copy link

Thank you for your fast reply! I fully understand and thank you again. Have a great day

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment