wp_img_tag_add_srcset_and_sizes_attr

函式
wp_img_tag_add_srcset_and_sizes_attr ( $image, $context, $attachment_id )
引數
  • (string) $image The HTML `img` tag where the attribute should be added.
    Required:
  • (string) $context Additional context to pass to the filters.
    Required:
  • (int) $attachment_id Image attachment ID.
    Required:
返回值
  • (string) Converted 'img' element with 'loading' attribute added.
定義位置
相關方法
wp_image_add_srcset_and_sizeswp_img_tag_add_width_and_height_attrwp_img_tag_add_loading_attrwp_img_tag_add_decoding_attrwp_iframe_tag_add_loading_attr
引入
5.5.0
棄用
-

wp_img_tag_add_srcset_and_sizes_attr是一個向HTML img標籤新增srcset和 sizes屬性的函式。srcset屬性根據裝置的解析度指定要使用的圖片,而 sizes屬性則指定圖片的大小。這可以通過減少為在頁面上顯示影象而需要下載的資料量來幫助提高效能。

在一個現有的`img’HTML標籤上新增`srcset’和`sizes’屬性。

function wp_img_tag_add_srcset_and_sizes_attr( $image, $context, $attachment_id ) {
	/**
	 * Filters whether to add the `srcset` and `sizes` HTML attributes to the img tag. Default `true`.
	 *
	 * Returning anything else than `true` will not add the attributes.
	 *
	 * @since 5.5.0
	 *
	 * @param bool   $value         The filtered value, defaults to `true`.
	 * @param string $image         The HTML `img` tag where the attribute should be added.
	 * @param string $context       Additional context about how the function was called or where the img tag is.
	 * @param int    $attachment_id The image attachment ID.
	 */
	$add = apply_filters( 'wp_img_tag_add_srcset_and_sizes_attr', true, $image, $context, $attachment_id );

	if ( true === $add ) {
		$image_meta = wp_get_attachment_metadata( $attachment_id );
		return wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id );
	}

	return $image;
}

常見問題

FAQs
檢視更多 >