WordPress:在自定义程序的图片中添加"srcset"和"sizes"属性 [英] Wordpress: adding ‘srcset’ and ‘sizes’ attributes to image from customizer
问题描述
Wordpress
会自动为所有来自帖子的图像添加 srcset
和 sizes
属性.太整齐了.
Wordpress
automatically adds srcset
and sizes
attributes to all images coming from posts. That’s very neat.
但是我如何让WordPress将这些属性添加到来自定制器输入的图像中?
就我而言:帖子的默认图片.当帖子中没有上传图像时,将显示该默认图像.它是由用户通过定制工具上传的,并使用 get_theme_mod
进行调用.
In my case: a default image for posts. That default image is displayed when no image was uploaded in a post. It’s uploaded by the user through the customizer and called using get_theme_mod
.
帖子中的图片(工作正常,添加了所有属性)
image from post (works fine, all attributes are added):
get_the_post_thumbnail($post->ID, 'news', array('class' => 'img-responsive'));
如果未提供图片:则加载默认图片(无"scrset"和"sizes" )
if no image is provided: the default image is loaded (no ’scrset’ and ’sizes’)
'<img src="' . esc_url( get_theme_mod( 'default_image' ) ) . '" alt="default image" class="img-responsive" />'
wp_image_add_srcset_and_sizes()
似乎是解决之道,但它需要我不知道从何处获取的属性.
wp_image_add_srcset_and_sizes()
seems to be the way to go but it requires attributes I don’t know where to get.
谢谢您的帮助!
推荐答案
此功能可以解决问题:
function create_responsive_image( $img ) {
$img_id = attachment_url_to_postid( $img );
$img_srcset = wp_get_attachment_image_srcset( $img_id );
$img_sizes = wp_get_attachment_image_sizes( $img_id );
return '<img src="' . $img . '" srcset="' . esc_attr( $img_srcset ) . '" sizes="' . esc_attr( $img_sizes ) . '">';
}
这篇关于WordPress:在自定义程序的图片中添加"srcset"和"sizes"属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!