wp_img_tag_add_auto_sizes()WP 6.7.0

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

Хуки из функции

Возвращает

Строку. The filtered image tag markup.

Использование

wp_img_tag_add_auto_sizes( $image ): string;
$image(строка) (обязательный)
The image tag markup being filtered.

Список изменений

С версии 6.7.0 Введена.

Код wp_img_tag_add_auto_sizes() WP 6.7.1

function wp_img_tag_add_auto_sizes( string $image ): string {
	/**
	 * Filters whether auto-sizes for lazy loaded images is enabled.
	 *
	 * @since 6.7.1
	 *
	 * @param boolean $enabled Whether auto-sizes for lazy loaded images is enabled.
	 */
	if ( ! apply_filters( 'wp_img_tag_add_auto_sizes', true ) ) {
		return $image;
	}

	$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.
	$loading = $processor->get_attribute( 'loading' );
	if ( ! is_string( $loading ) || 'lazy' !== strtolower( trim( $loading, " \t\f\r\n" ) ) ) {
		return $image;
	}

	/*
	 * Bail early if the image doesn't have a width attribute.
	 * Per WordPress Core itself, lazy-loaded images should always have a width attribute.
	 * However, it is possible that lazy-loading could be added by a plugin, where we don't have that guarantee.
	 * As such, it still makes sense to ensure presence of a width attribute here in order to use `sizes=auto`.
	 */
	$width = $processor->get_attribute( 'width' );
	if ( ! is_string( $width ) || '' === $width ) {
		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();
}