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

Commit b5b3d26

Browse files
committed
Update wp_add_lazy_load_attributes()
Filter eachg tag after adding the `loading` attribute. Change priority to 25, after other "display" filters.
1 parent dcc6a32 commit b5b3d26

File tree

1 file changed

+20
-7
lines changed

1 file changed

+20
-7
lines changed

wp-lazy-loading.php

Lines changed: 20 additions & 7 deletions
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,29 @@ 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+
$old_html = $matches[0];
145+
$new_html = str_replace( '<img', '<img loading="lazy"', $old_html );
146+
147+
/**
148+
* Filters the tag HTML after adding the `loading` attribute.
149+
*
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`.
152+
*
153+
* @since (TBD)
154+
*
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.
158+
* @param string $context Optional. Additional context. Defaults to `current_filter()`.
159+
*/
160+
return apply_filters( 'wp_add_lazy_loading_to_img', $new_html, $old_html, $content, $context );
147161
}
148162

149163
return $matches[0];
150164
},
151165
$content
152166
);
153167
}
154-

0 commit comments

Comments
 (0)