我最终使用了在codepen上找到的一个函数,并对其进行了轻微的修改。编辑:还值得注意的是,wp\\u get\\u attachment\\u image\\u src()为所有图像宽度返回了0,因此我创建了自己的宽度数组,并以这种方式分配了它们。(希望我能找到这些简洁的内置方法的用途)
function srcset_post_thumbnail($defaultSize = \'m\')
{
$thumbnailSizes = [
\'xs\',
\'s\',
\'m\',
\'l\',
\'xl\'
];
$html = \'<img sizes="\';
$html .= \'(max-width: 30em) 100vw, \';
$html .= \'(max-width: 50em) 50vw, \';
$html .= \'calc(33vw - 100px)" \';
$html .= \'srcset="\';
$thumb_id = get_post_thumbnail_id();
for ($i = 0; $i < count($thumbnailSizes); $i++) {
$thumb = wp_get_attachment_image_src($thumb_id, $thumbnailSizes[$i], true);
$url = $thumb[0];
$width = $thumb[1];
$html .= $url . \' \' . $width . \'w\';
if ($i < count($thumbnailSizes) - 1) {
$html .= \', \';
}
}
$alt = get_post_meta($thumb_id, \'_wp_attachment_image_alt\', true);
$thumbMedium = wp_get_attachment_image_src($thumb_id, $defaultSize, true);
$html .= \'" \';
$html .= \'src="\' . $thumbMedium[0] . \'" alt="\' . $alt . \'">\';
return $html;
}