SketchBookkeeper
2/26/2018 - 6:01 PM

Lazyload iFrames

WordPress and ACF

/**
 * Lazyload iFrames
 * Return a string of the supplied iframe markup that includes lazyload attributes
 * @param string $iframe string generated through ACF oembed field
 * @return string
 */
function base_display_lazyload_iframe( $iframe ) {
	// Bail if $iframe is not provided or if $iframe is not a string
	if ( !$iframe || gettype( $iframe ) !== 'string') {
		return '';
	}

	$allow_tags['iframe'] = array(
		'align' => true,
		'width' => false,
		'height' => false,
		'frameborder' => true,
		'name' => true,
		'src' => true,
		'id' => true,
		'class' => true,
		'style' => true,
		'scrolling' => true,
		'marginwidth' => true,
		'marginheight' => true,
	);

	// Santatize $iframe
	$iframe = wp_kses( $iframe, $allow_tags );

	// Inject lazyload attributes
	$iframe = str_replace( 'src', 'class="c-block-video__iframe lazyload" data-src', $iframe );

	echo $iframe;
}