Hello,
I have a question regarding the output of the oembed-field: Is it possible to change the ‘src’-attribute of an iframe to a ‘data-src’-attribute? I want to lazyload youtube videos with the great lazysizes-Plugin.
I have already added the class=”lazyload” to the outputted iframe. But I don’t know how to replace the ‘src’-attribute to a ‘data-src’-attribute.
This is what I used as a reference:
<?php
// get iframe HTML
$iframe = get_field('oembed');
// use preg_match to find iframe src
preg_match('/src="(.+?)"/', $iframe, $matches);
$src = $matches[1];
// add extra params to iframe src
$params = array(
'controls' => 0,
'hd' => 1,
'autohide' => 1
);
$new_src = add_query_arg($params, $src);
$iframe = str_replace($src, $new_src, $iframe);
// add extra attributes to iframe html
$attributes = 'frameborder="0" class="lazyload"';
$iframe = str_replace('></iframe>', ' ' . $attributes . '></iframe>', $iframe);
// echo $iframe
echo $iframe;
?>
Any kind of help would be greatly appreciated.
Thanks!
I don’t know if you’ve found a solution. I will write my solution here, because your Topic is well ranked by Google and here no answer is written.
An here comes my solution.
paste preg_replace:
preg_replace('~<iframe[^>]*\K(?=src)~i','data-',$iframe);
Full Snippet:
<?php
// get iframe HTML
$iframe = get_field('oembed');
// use preg_match to find iframe src
preg_match('/src="(.+?)"/', $iframe, $matches);
$src = $matches[1];
// add extra params to iframe src
$params = array(
'controls' => 0,
'hd' => 1,
'autohide' => 1
);
$new_src = add_query_arg($params, $src);
$iframe = str_replace($src, $new_src, $iframe);
// add extra attributes to iframe html
$attributes = 'frameborder="0" class="lazyload"';
// use preg_replace to change iframe src to data-src
$iframe = preg_replace('~<iframe[^>]*\K(?=src)~i','data-',$iframe);
$iframe = str_replace('></iframe>', ' ' . $attributes . '></iframe>', $iframe);
// echo $iframe
echo $iframe;
?>
@matthias-honert thank you!
$iframe = preg_replace(‘~<iframe[^>]*\K(?=src)~i’,’data-‘,$iframe);
sorted it for me too after hours of looking!!! 🙂
The topic ‘oEmbed: Change iframe src to "data-src"’ is closed to new replies.
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.