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

Commit 20f8b8c

Browse files
authored
Merge pull request #10 from WordPress/add/filter-for-each-tag
Add filtering for each tag after adding the loading attribute
2 parents 68712b5 + a23a342 commit 20f8b8c

File tree

1 file changed

+27
-7
lines changed

1 file changed

+27
-7
lines changed

wp-lazy-loading.php

+27-7
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,8 @@
3232
function _wp_lazy_loading_initialize_filters() {
3333
// The following filters would be merged into core.
3434
foreach ( array( 'the_content', 'the_excerpt', 'comment_text', 'widget_text_content' ) as $filter ) {
35-
// Before parsing blocks and shortcodes.
36-
// TODO: Comments do not support images. Revisit.
37-
// TODO: This should not exclude images from dynamic blocks and shortcodes. Look at fixing the filter priority.
38-
add_filter( $filter, 'wp_add_lazy_load_attributes', 8 );
35+
// After parsing blocks and shortcodes.
36+
add_filter( $filter, 'wp_add_lazy_load_attributes', 25 );
3937
}
4038

4139
// The following filters are only needed while this is a feature plugin.
@@ -141,14 +139,36 @@ function wp_add_lazy_load_attributes( $content, $context = null ) {
141139

142140
return preg_replace_callback(
143141
'/<img\s[^>]+>/',
144-
function( array $matches ) {
142+
function( array $matches ) use( $content, $context ) {
145143
if ( ! preg_match( '/\sloading\s*=/', $matches[0] ) ) {
146-
return str_replace( '<img', '<img loading="lazy"', $matches[0] );
144+
$tag_html = $matches[0];
145+
146+
/**
147+
* Filters the `loading` attribute value. Default `lazy`.
148+
*
149+
* Returning `false` or an empty string will not add the attribute.
150+
* Returning `true` will add the default value.
151+
*
152+
* @since (TBD)
153+
*
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.
157+
* @param string $context Optional. Additional context. Defaults to `current_filter()`.
158+
*/
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+
}
147168
}
148169

149170
return $matches[0];
150171
},
151172
$content
152173
);
153174
}
154-

0 commit comments

Comments
 (0)