|
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,29 @@ 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 | + $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 ); |
147 | 161 | } |
148 | 162 |
|
149 | 163 | return $matches[0]; |
150 | 164 | }, |
151 | 165 | $content |
152 | 166 | ); |
153 | 167 | } |
154 | | - |
|
0 commit comments