在 ACF 中使用 srcset 作为背景图片

Using srcset for background image in ACF

我正在使用 ACF 来允许客户上传将用作主页全屏背景的图像。图像会因星期几而异。我已经为背景图像创建了自定义图像大小,并且我有一个函数可以查询服务器的星期几并找到相应的图像。我无法将函数设置为 return 正确的图像大小。

这是我的函数:

function my_custom_background () { 

$today = date('l');
$image = get_field (strtolower($today));
$size = 'auto'; // (thumbnail, medium, large, full or custom size)
$backgroundImg = wp_get_attachment_image ( $image, $size );


?><style>body.page-id-5 {background-image: url( '<?php echo $backgroundImg; ?>'); }</style><?php
}

add_action('wp_head', 'my_custom_background');

这是呈现的内容:

background-image: url( '<img width="1920" height="1258" src="http://dev.whydidibother.com/klwdp/jumpstart-full-screen-image-daily-change-site/wp-content/uploads/sites/6/2017/10/amazing-beautiful-breathtaking-clouds.jpg" class="attachment-auto size-auto" alt="" srcset="http://dev.whydidibother.com/klwdp/jumpstart-full-screen-image-daily-change-site/wp-content/uploads/sites/6/2017/10/amazing-beautiful-breathtaking-clouds.jpg 1920w, http://dev.whydidibother.com/klwdp/jumpstart-full-screen-image-daily-change-site/wp-content/uploads/sites/6/2017/10/amazing-beautiful-breathtaking-clouds-300x197.jpg 300w, http://dev.whydidibother.com/klwdp/jumpstart-full-screen-image-daily-change-site/wp-content/uploads/sites/6/2017/10/amazing-beautiful-breathtaking-clouds-768x503.jpg 768w, http://dev.whydidibother.com/klwdp/jumpstart-full-screen-image-daily-change-site/wp-content/uploads/sites/6/2017/10/amazing-beautiful-breathtaking-clouds-1024x671.jpg 1024w, http://dev.whydidibother.com/klwdp/jumpstart-full-screen-image-daily-change-site/wp-content/uploads/sites/6/2017/10/amazing-beautiful-breathtaking-clouds-1200x786.jpg 1200w, http://dev.whydidibother.com/klwdp/jumpstart-full-screen-image-daily-change-site/wp-content/uploads/sites/6/2017/10/amazing-beautiful-breathtaking-clouds-800x524.jpg 800w, http://dev.whydidibother.com/klwdp/jumpstart-full-screen-image-daily-change-site/wp-content/uploads/sites/6/2017/10/amazing-beautiful-breathtaking-clouds-500x328.jpg 500w" sizes="(max-width: 1920px) 100vw, 1920px" />');

感谢任何建议。

如果您查看 Wordpress reference for wp_get_attachment_image,您会发现此函数 return 是一个 html 元素。我建议将您的 ACF 图像字段设置为 return 图像对象(实际上 return 是一个数组),然后按如下方式获取适当的大小:

$image = get_field(strtolower($today));
echo $image['sizes']['large']; // thumbnail, medium, large, full or custom

另请参阅 image field 的 ACF 文档("Customized display (arrray)" 部分)。