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

时间:2017-10-08 18:08:09

标签: wordpress advanced-custom-fields srcset

我使用ACF允许客户端上传将在主页上用作全屏背景的图像。图像将根据星期几而有所不同。我已经为背景图像创建了自定义图像大小,我有一个功能,它将查询服务器的星期几并找到相应的图像。我无法使函数返回正确的图像大小。

这是我的功能:

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" />');

感谢任何建议。

1 个答案:

答案 0 :(得分:0)

如果查看Wordpress reference for wp_get_attachment_image,您会看到此函数返回一个html元素。我建议您设置ACF图像字段以返回图像对象(实际上返回一个数组),然后按如下方式获得正确的大小:

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

另请参阅image field的ACF文档(“自定义显示(arrray)”部分)。