Generate YouTube image thumbnail in a Gutenberg block – ACF + Timber

Question

I use Timber + ACF + Gutenberg blocks for a project. I’m trying to build a simple back office for students.

I created a Gutenberg block with ACF : an embed type field that I called media-video

In the back office the students will enter a YouTube url : https://youtu.be/BHACKCNDMW8 or https://www.youtube.com/watch?v=BHACKCNDMW8

But I would like to generate a YouTube image thumbnail from this url, like that : https://img.youtube.com/vi/<insert-youtube-video-id-here>/sddefault.jpg

For that I need to extract the YouTube ID but I don’t know how to proceed.

I got two problems :
– WordPress embed field output is an iframe when I need to get the url
– Students will be able to create multiple media-video Gutenberg blocks

To start I managed to get the urls with this loop in single.php :

if ( has_blocks( $post->post_content ) ) {
    $blocks = parse_blocks( $post->post_content );

    foreach ( $blocks as $block ) {
        if ( $block['blockName'] === 'acf/media-video' ) {
            $media_video_url = $block['attrs']['data']['media_video'];
            print_r($media_video_url);
        }
    }
}

But after I don’t know how to recover this URL and to put it back in the Gutenberg block.

Gutenberg bloc-media-video.twig :

<article class="media-video bloc">
    <div class="media-video__content type-video">
        <div class="media-video__container">
            {{ fields.media_video }}
        </div>
    </div>
</article>

Then I thought of extracting the YouTube ID with a TWIG macro :

{{ _self.extractYouTubeIdAndProvideiFrame('the-youtube-url') }}

    {% macro extractYouTubeIdAndProvideiFrame(url) %}
        {% set ytregex1 = '/^(?:https?://)?(?:www.)?(?:youtu.be/|youtube.com)(?:/embed/|/v/|/watch?v=||/watch?.+&v=)/' %}
        {% set ytregexTrailingSlash = '/(/)$/' %}
        {% set ytregexTrailingVariables = '/(&+.*)/' %}
        {% set youtubeid = url | replace(ytregex1, '') | replace(ytregexTrailingSlash, '') | replace(ytregexTrailingVariables, '') %}
        <img src="https://img.youtube.com/vi/{{ youtubeid }}/sddefault.jpg">
    {% endmacro %}

But the regex don’t work.

I don’t know which solution to take. Can I have some help please ?

0
, Jandon 3 years 2020-06-06T07:11:08-05:00 0 Answers 103 views 0

Leave an answer

Browse
Browse