函数文档

wp_img_tag_add_decoding_attr()

💡 云策文档标注

概述

wp_img_tag_add_decoding_attr() 是一个已弃用的 WordPress 函数,用于向 HTML img 标签添加 decoding 属性,以控制浏览器解码图像的方式。开发者可通过 wp_img_tag_add_decoding_attr 过滤器修改属性值。

关键要点

  • 函数已弃用,自 WordPress 6.4.0 起推荐使用 wp_img_tag_add_loading_optimization_attrs() 替代。
  • decoding 属性允许设置 async、sync 或 auto 值,默认添加 decoding="async"。
  • 函数接受两个参数:$image(img 标签字符串)和 $context(上下文字符串),返回添加属性后的 img 标签。
  • 仅当 img 标签包含 src=" 时才添加属性,确保排除转义 JSON 等情况。
  • 提供 wp_img_tag_add_decoding_attr 过滤器,允许开发者自定义属性值或移除属性。

代码示例

function wp_img_tag_add_decoding_attr( $image, $context ) {
    _deprecated_function( __FUNCTION__, '6.4.0', 'wp_img_tag_add_loading_optimization_attrs()' );

    if ( ! str_contains( $image, ' src="' ) ) {
        return $image;
    }

    $value = apply_filters( 'wp_img_tag_add_decoding_attr', 'async', $image, $context );

    if ( in_array( $value, array( 'async', 'sync', 'auto' ), true ) ) {
        $image = str_replace( '<img', '<img decoding="' . esc_attr( $value ) . '"', $image );
    }

    return $image;
}

注意事项

  • 函数已弃用,新代码应避免使用,改用 wp_img_tag_add_loading_optimization_attrs()。
  • decoding 属性值必须为 async、sync 或 auto 之一,否则不会添加。
  • 过滤器 wp_img_tag_add_decoding_attr 可用于覆盖默认值或返回 false/null 以移除属性。

📄 原文内容

Adds decoding attribute to an img HTML tag.

Description

The decoding attribute allows developers to indicate whether the browser can decode the image off the main thread (async), on the main thread (sync) or as determined by the browser (auto).

By default WordPress adds decoding="async" to images but developers can use the ‘wp_img_tag_add_decoding_attr’ filter to modify this to remove the attribute or set it to another accepted value.

See also

Parameters

$imagestringrequired
The HTML img tag where the attribute should be added.
$contextstringrequired
Additional context to pass to the filters.

Return

string Converted img tag with decoding attribute added.

Source

function wp_img_tag_add_decoding_attr( $image, $context ) {
	_deprecated_function( __FUNCTION__, '6.4.0', 'wp_img_tag_add_loading_optimization_attrs()' );

	/*
	 * Only apply the decoding attribute to images that have a src attribute that
	 * starts with a double quote, ensuring escaped JSON is also excluded.
	 */
	if ( ! str_contains( $image, ' src="' ) ) {
		return $image;
	}

	/** This action is documented in wp-includes/media.php */
	$value = apply_filters( 'wp_img_tag_add_decoding_attr', 'async', $image, $context );

	if ( in_array( $value, array( 'async', 'sync', 'auto' ), true ) ) {
		$image = str_replace( '<img ', '<img decoding="' . esc_attr( $value ) . '" ', $image );
	}

	return $image;
}

Hooks

apply_filters( ‘wp_img_tag_add_decoding_attr’, string|false|null $value, string $image, string $context )

Filters the decoding attribute value to add to an image. Default async.

Changelog

Version Description
6.4.0 Deprecated. Use wp_img_tag_add_loading_optimization_attrs() instead.
6.1.0 Introduced.