Skip to content
This repository was archived by the owner on Dec 23, 2020. It is now read-only.

Commit a23a342

Browse files
committed
Replace the "wp_add_lazy_loading_to_img" filter with the more targeted "wp_set_image_loading_attr".
1 parent 395e126 commit a23a342

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

wp-lazy-loading.php

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -141,23 +141,30 @@ function wp_add_lazy_load_attributes( $content, $context = null ) {
141141
'/<img\s[^>]+>/',
142142
function( array $matches ) use( $content, $context ) {
143143
if ( ! preg_match( '/\sloading\s*=/', $matches[0] ) ) {
144-
$old_html = $matches[0];
145-
$new_html = str_replace( '<img', '<img loading="lazy"', $old_html );
144+
$tag_html = $matches[0];
146145

147146
/**
148-
* Filters the tag HTML after adding the `loading` attribute.
147+
* Filters the `loading` attribute value. Default `lazy`.
149148
*
150-
* The variable part of the filter name is the filtered tag's name. For example for `img`
151-
* the filter would become `wp_add_lazy_loading_to_img`.
149+
* Returning `false` or an empty string will not add the attribute.
150+
* Returning `true` will add the default value.
152151
*
153152
* @since (TBD)
154153
*
155-
* @param string $new_html The tag's HTML after adding the attribute.
156-
* @param string $old_html The tag's HTML before adding the attribute.
157-
* @param string $content The HTML content that is being filtered.
154+
* @param string $default The filtered value, defaults to `lazy`.
155+
* @param string $tag_html The tag's HTML.
156+
* @param string $content The HTML containing the image tag.
158157
* @param string $context Optional. Additional context. Defaults to `current_filter()`.
159158
*/
160-
return apply_filters( 'wp_add_lazy_loading_to_img', $new_html, $old_html, $content, $context );
159+
$value = apply_filters( 'wp_set_image_loading_attr', 'lazy', $tag_html, $content, $context );
160+
161+
if ( $value ) {
162+
if ( ! in_array( $value, array( 'lazy', 'eager' ), true ) ) {
163+
$value = 'lazy';
164+
}
165+
166+
return str_replace( '<img', '<img loading="' . $value . '"', $tag_html );
167+
}
161168
}
162169

163170
return $matches[0];

0 commit comments

Comments
 (0)