Skip to content

Commit 32b9abc

Browse files
Use WP_HTML_Tag_Processor in auto_sizes_update_content_img_tag
1 parent 1859613 commit 32b9abc

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

plugins/auto-sizes/hooks.php

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -57,24 +57,32 @@ function auto_sizes_update_content_img_tag( $html ): string {
5757
$html = '';
5858
}
5959

60+
$processor = new WP_HTML_Tag_Processor( $html );
61+
62+
// Bail if there is no IMG tag.
63+
if ( ! $processor->next_tag( array( 'tag_name' => 'IMG' ) ) ) {
64+
return $html;
65+
}
66+
6067
// Bail early if the image is not lazy-loaded.
61-
if ( false === strpos( $html, 'loading="lazy"' ) ) {
68+
if ( 'lazy' !== $processor->get_attribute( 'loading' ) ) {
6269
return $html;
6370
}
6471

72+
$sizes = $processor->get_attribute( 'sizes' );
73+
6574
// Bail early if the image is not responsive.
66-
if ( 1 !== preg_match( '/sizes="([^"]+)"/', $html, $match ) ) {
75+
if ( ! is_string( $sizes ) ) {
6776
return $html;
6877
}
6978

7079
// Don't add 'auto' to the sizes attribute if it already exists.
71-
if ( auto_sizes_attribute_includes_valid_auto( $match[1] ) ) {
80+
if ( auto_sizes_attribute_includes_valid_auto( $sizes ) ) {
7281
return $html;
7382
}
7483

75-
$html = str_replace( 'sizes="', 'sizes="auto, ', $html );
76-
77-
return $html;
84+
$processor->set_attribute( 'sizes', "auto, $sizes" );
85+
return $processor->get_updated_html();
7886
}
7987
add_filter( 'wp_content_img_tag', 'auto_sizes_update_content_img_tag' );
8088

0 commit comments

Comments
 (0)