Support

Account

Home Forums ACF PRO oEmbed: Change iframe src to "data-src"

Solving

oEmbed: Change iframe src to "data-src"

  • 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!!! 🙂

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘oEmbed: Change iframe src to "data-src"’ is closed to new replies.