Support

Account

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

  • 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;
    
    ?>