Support

Account

Home Forums Add-ons Flexible Content Field Fetch YouTube Thumbnail during oEmbed dataparse

Solving

Fetch YouTube Thumbnail during oEmbed dataparse

  • Hi,

    On my site I have a flexible content field. One of the rows is for video, with 2 fields. The first is “url” (an oEmbed) and the second is “thumbnail” (a URL).

    What I’m trying to achieve is when I type or paste a URL into the oEmbed field, I want to automatically populate the thumbnail field with the thumbnail URL from YouTube.

    Is this possible please?

  • Did you ever find a solution for this?

  • 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];
    }
    
Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Fetch YouTube Thumbnail during oEmbed dataparse’ is closed to new replies.