
如何在移动设备上预览WordPress网站
wp_img_tag_add_loading_attr ( $image, $context )
wp_img_tag_add_loading_attr是一个给HTML img标签添加加载属性的函数。加载属性指定了图片的加载方式,它可以取三个值。”eager”表示立即加载,”lazy”表示只在图像进入视图时加载,”auto”表示让浏览器决定。
为`img`HTML标签添加`loading`属性。
function wp_img_tag_add_loading_attr( $image, $context ) { // Get loading attribute value to use. This must occur before the conditional check below so that even images that // are ineligible for being lazy-loaded are considered. $value = wp_get_loading_attr_default( $context ); // Images should have source and dimension attributes for the `loading` attribute to be added. if ( false === strpos( $image, ' src="' ) || false === strpos( $image, ' width="' ) || false === strpos( $image, ' height="' ) ) { return $image; } /** * Filters the `loading` attribute value to add to an image. Default `lazy`. * * Returning `false` or an empty string will not add the attribute. * Returning `true` will add the default value. * * @since 5.5.0 * * @param string|bool $value The `loading` attribute value. Returning a falsey value will result in * the attribute being omitted for the image. * @param string $image The HTML `img` tag to be filtered. * @param string $context Additional context about how the function was called or where the img tag is. */ $value = apply_filters( 'wp_img_tag_add_loading_attr', $value, $image, $context ); if ( $value ) { if ( ! in_array( $value, array( 'lazy', 'eager' ), true ) ) { $value = 'lazy'; } return str_replace( '<img', '<img loading="' . esc_attr( $value ) . '"', $image ); } return $image; }