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 : or
But I would like to generate a YouTube image thumbnail from this url, like that : /<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\)(?:\\/embed\\/|\\/v\\/|\\/watch\\?v=||\\/watch\\\?.+&v=)/' %}
{% set ytregexTrailingSlash = '/(\\/)$/' %}
{% set ytregexTrailingVariables = '/(&+.*)/' %}
{% set youtubeid = url | replace(ytregex1, '') | replace(ytregexTrailingSlash, '') | replace(ytregexTrailingVariables, '') %}
<img src="/{{ youtubeid }}/sddefault.jpg">
{% endmacro %}
But the regex don't work.
I don't know which solution to take. Can I have some help please ?