wpseek.com
A WordPress-centric search engine for devs and theme authors



wp_img_tag_add_auto_sizes › WordPress Function

Since6.7.0
Deprecatedn/a
wp_img_tag_add_auto_sizes ( $image )
Parameters:
  • (string) $image The image tag markup being filtered.
    Required: Yes
Returns:
  • (string) The filtered image tag markup.
Defined at:
Codex:

Adds 'auto' to the sizes attribute to the image, if the image is lazy loaded and does not already include it.



Source

function wp_img_tag_add_auto_sizes( string $image ): string {
	$processor = new WP_HTML_Tag_Processor( $image );

	// Bail if there is no IMG tag.
	if ( ! $processor->next_tag( array( 'tag_name' => 'IMG' ) ) ) {
		return $image;
	}

	// Bail early if the image is not lazy-loaded.
	$value = $processor->get_attribute( 'loading' );
	if ( ! is_string( $value ) || 'lazy' !== strtolower( trim( $value, " \t\f\r\n" ) ) ) {
		return $image;
	}

	$sizes = $processor->get_attribute( 'sizes' );

	// Bail early if the image is not responsive.
	if ( ! is_string( $sizes ) ) {
		return $image;
	}

	// Don't add 'auto' to the sizes attribute if it already exists.
	if ( wp_sizes_attribute_includes_valid_auto( $sizes ) ) {
		return $image;
	}

	$processor->set_attribute( 'sizes', "auto, $sizes" );
	return $processor->get_updated_html();
}