|
32 | 32 | function _wp_lazy_loading_initialize_filters() {
|
33 | 33 | // The following filters would be merged into core.
|
34 | 34 | 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 ); |
39 | 37 | }
|
40 | 38 |
|
41 | 39 | // 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 ) {
|
141 | 139 |
|
142 | 140 | return preg_replace_callback(
|
143 | 141 | '/<img\s[^>]+>/',
|
144 |
| - function( array $matches ) { |
| 142 | + function( array $matches ) use( $content, $context ) { |
145 | 143 | 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 | + } |
147 | 168 | }
|
148 | 169 |
|
149 | 170 | return $matches[0];
|
150 | 171 | },
|
151 | 172 | $content
|
152 | 173 | );
|
153 | 174 | }
|
154 |
| - |
|
0 commit comments