Wordpress
会自动为来自帖子的所有图片添加srcset
和sizes
属性。那非常整洁。
但是如何让WordPress将这些属性添加到来自自定义程序输入的图像中?
在我的情况下:帖子的默认图片。在帖子中没有上传图像时显示该默认图像。它由用户通过自定义程序上传,并使用get_theme_mod
进行调用。
图片(工作正常,所有属性都已添加):
get_the_post_thumbnail($post->ID, 'news', array('class' => 'img-responsive'));
如果没有提供图片:加载默认图片(没有'scrset'和'尺寸')
'<img src="' . esc_url( get_theme_mod( 'default_image' ) ) . '" alt="default image" class="img-responsive" />'
wp_image_add_srcset_and_sizes()
似乎是要走的路,但它需要属性,我不知道从哪里得到。
感谢您的帮助!
答案 0 :(得分:2)
this function does the trick:
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 ) . '">';
}