I am trying to automatically add a video thumbnail from Vimeo or YouTube as the featured image when a new custom post type video is add/updated.
The video ID is an advanced custom field.
Here’s my non-working code:
/**
* Gets a vimeo thumbnail url
* @param mixed $id A vimeo id (ie. 1185346)
* @return thumbnail's url
*/
function getVimeoThumb($id) {
$data = file_get_contents("http://vimeo.com/api/v2/video/".$id.".json");
$data = json_decode($data);
return $data[0]->thumbnail_large;
}
/**
* Gets a youtube thumbnail url
* @param mixed $id A youtube id
* @return thumbnail's url
*/
function getYoutubeThumb($id) {
$data = file_get_contents("https://www.googleapis.com/youtube/v3/videos?key=AIzaSyB-gLbxJIJCGEwmDlC3sE9ml5DJ3tAaWnE&part=snippet&id=".$id);
$data = json_decode($data);
return $json->items[0]->snippet->thumbnails->medium->url;
}
// Add featured image for videos
function addVideoThumb($post_ID) {
if(!has_post_thumbnail($post_ID)):
if(get_field("source", $post_ID) == "youtube"):
$videoID = get_field("youtube_video_id", $post_ID);
$imageURL = getYoutubeThumb($videoID);
else:
$videoID = get_field("vimeo_video_id", $post_ID);
$imageURL = getVimeoThumb($videoID);
endif;
//echo $imageURL;
// download image from url
$tmp = download_url($imageURL);
$file = array(
'name' => basename($imageURL),
'tmp_name' => $tmp
);
// create attachment from the uploaded image
$attachment_id = media_handle_sideload($file, $post_ID);
// set the featured image
update_post_meta($post_ID, '_thumbnail_id', $attachment_id);
endif;
}
add_action('save_post_interel-tv-videos', 'addVideoThumb', 10, 3);
The function doesn’t seem to be triggered at all as I tried to add a JavaScript alert to it and nothing pops up.
Any help?
Thanks in advance!