Skip to content

Instantly share code, notes, and snippets.

@adamsilverstein
Last active November 22, 2023 22:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamsilverstein/e280062004c38629fc029b6d267bff91 to your computer and use it in GitHub Desktop.
Save adamsilverstein/e280062004c38629fc029b6d267bff91 to your computer and use it in GitHub Desktop.
Add lazy loading to oEmbed iframes (in WordPress)
<?php
/**
* Add lazy loading to oEmbed iframes.
*
* @wordpress-plugin
* Plugin Name: Lazy Load oEmbeds.
* Description: Add lazy loading to oEmbed iframes.
* Plugin URI:
* Version: 1.0.0
* Author: Adam Silverstein, Google
* License: Apache License 2.0
* License URI: https://www.apache.org/licenses/LICENSE-2.0
*/
// See https://core.trac.wordpress.org/ticket/58773
function add_lazy_loading_attr_to_oembed_iframes( $iframe ) {
// Skip oEmbeds without iframes.
if ( ! preg_match_all( '/<(iframe)\s[^>]+>/', $iframe, $matches, PREG_SET_ORDER ) ) {
return $iframe;
}
// Skip when lazy loading is disabled.
if ( ! wp_lazy_loading_enabled( 'iframe', 'oembed' ) ) {
return $iframe;
}
// Iterate through all iframes and add loading attribute (only one iframe is expected).
foreach ( $matches as $match ) {
$filtered_iframe = $match[0];
// Add 'loading' attribute if applicable.
if ( ! str_contains( $filtered_iframe, ' loading=' ) ) {
$filtered_iframe = wp_iframe_tag_add_loading_attr( $filtered_iframe, 'oembed' );
}
if ( $filtered_iframe !== $match[0] ) {
$iframe = str_replace( $match[0], $filtered_iframe, $iframe );
}
return $iframe;
}
}
add_filter( 'embed_oembed_html', 'add_lazy_loading_attr_to_oembed_iframes' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment