First of all, let me mention that I have already looked at the following two similar questions:
- Is it possible to modify the default YouTube embed attributes string?
- Filter oembeds tags to modify iframe attributes
But both of them are pre Gutenberg era. So, while using Gutenberg oEmbed block to embed a YouTube video if I want to add a srcdoc
attribute to it, is there a way to do it? Or do I have to create my custom block for it? I'm really confused here about whether or not the wp_embed_handler_youtube
or embed_oembed_html
filters will help me here.
Current Embedding Sutuation
So, currently when you use Gutenberg oEmbed block to embed a YouTube video, it basically adds the following iframe
:
<iframe
loading="lazy"
title="Some Title"
width="680"
height="383"
src="https://www.youtube.com/embed/<VIDEO_ID>?feature=oembed"
frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen=""></iframe>
Which is wrapped withing a few HTML element added by WP Core.
What I am looking for
What I am looking for here is to add the srcdoc
attribute to that YouTube embeds to better lazy load the video. So, it would become something like:
<iframe
width="560"
height="315"
loading="lazy"
src="https://www.youtube.com/embed/<VIDEO_ID>"
srcdoc="<style>*{padding:0;margin:0;overflow:hidden}html,body{height:100%}img,span{position:absolute;width:100%;top:0;bottom:0;margin:auto}span{height:1.5em;text-align:center;font:48px/1.5 sans-serif;color:white;text-shadow:0 0 0.5em black}</style><a href=https://www.youtube.com/embed/<VIDEO_ID>?autoplay=1><img src=https://img.youtube.com/vi/<VIDEO_ID>/maxresdefault.jpg alt='Types of Succulents -- Cold Hardy and Soft Succulents'><span>▶</span></a>"
title="Types of Succulents -- Cold Hardy and Soft Succulents"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>
Does anyone have any idea about how to accomplish this while using Gutenberg oEmbed Block to embed the YouTube video? Any suggestions and help are very welcome.
wp_embed_handler_youtube
filter. Is there a way to get the Video ID? Or do I have to write my own RegEx to parse the URL and get the Video ID out of it? That was my second question in case any of those above methods works.