Wordpress:将“srcset”和“尺寸”属性添加到自定义工具

时间:2017-08-04 10:11:25

标签: php wordpress image themes srcset

Wordpress会自动为来自帖子的所有图片添加srcsetsizes属性。那非常整洁。

但是如何让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()似乎是要走的路,但它需要属性,我不知道从哪里得到。

感谢您的帮助!

1 个答案:

答案 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 ) . '">';
}