Snippets

nvisionsolution Defer Oembed

Created by Chris Satchell
// Defer Loading ACF oEmbed Content
// 
// Replace 'src' with 'data-src' for lazy-loading with JS.
//
// @param $acf The ACF Field using get_field
function nvision_defer_oembed( $acf ) {

    // use preg_match to find iframe src
    preg_match( '/src="(.+?)"/', $acf, $matches );
    $src = $matches[1];

    // get src url by removing the src attribute name + equals, and quotes
    $src_value = str_replace( ['src=', '"'], '', $src );

    // remove the src from the iframe so that it does not load
    $acf = str_replace( $src, '', $acf );

    // add [data-src] and .js-defer-oembed to iframe html
    $attributes = ' data-src="' . $src_value . '" class="js-defer-oembed" ';

    $acf = str_replace( '></iframe>', ' ' . $attributes . '></iframe>', $acf );

    // echo $iframe
    echo $acf;
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.