Home › Forums › Add-ons › Flexible Content Field › Fetch YouTube Thumbnail during oEmbed dataparse › Reply To: Fetch YouTube Thumbnail during oEmbed dataparse
Yes, it is possible.
You first need to extract the video IF from the video URL and construct the image URL, this URL will be different base on when the video was uploaded to youtube, newer videos have a better thumbnail.
with the URLs first you try to sideload the new URL, if this returns an error then you try to sideload the old url.
media_sideload_image() returns an image ID or an error.
You then use the image ID if successful to update the field
// in this code $youtube_id is the video id extracted from the video url
// I don't have code for this
// new video thumb url
$youtube_image_url = 'https://i3.ytimg.com/vi/'.$youtube_id.'/maxresdefault.jpg';
// try to sideload
$image_id = media_sideload_image($youtube_image_url, NULL, NULL, 'id');
if (is_wp_error($image_id)) {
// failed to sideload image
// old video thumb url
$youtube_image_url = 'https://img.youtube.com/vi/'.$youtube_id.'/0.jpg';
// try to sideload
$image_id = media_sideload_image($youtube_image_url, NULL, NULL, 'id');
}
// if $image_id is not a error then update the field
if (!is_wp_error($image_id)) {
update_field('your-imge-field-name', $image_id, $post_id);
}
I do this by extracting the youtube ID from an oembed field and not a url field. As I said above, I do not have code to extract from a URL because these vary. However ACF returns a constant src value.
$video_code = get_field('oembed-field-name', $post_id);
preg_match('#/embed/([^\?]+)#', $video_code, $matches);
if (!empty($matches[1])) {
$youtube_id = $matches[1];
}
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.