[英]How to dynamically set a background-image size?
I have a 1600 x 1000 image that's used as a background image, with an ACF repeater field that outputs each section, each with its own unique background image.我有一个 1600 x 1000 的图像用作背景图像,带有一个输出每个部分的 ACF 转发器字段,每个部分都有自己独特的背景图像。 I'm concerned about mobile.
我很担心手机。 Is there a way to dynamically populate the background image size based on
wp_if_mobile()
?有没有办法根据
wp_if_mobile()
动态填充背景图像大小? Here's a bit of my code:这是我的一些代码:
$banners = get_field('home_page_banner');
foreach ($banners as $banner) {
$background_image = $banner['background_image']; //Here's the variable, which is set to ACF Image Field Array.
//additional vars here
echo '<div class="home-page-banner grayscale" style="background-image: url(' . esc_url($background_image['url']) . '); ">'; // Here's where the background-image goes
//other stuff in here
</div>';
$result_count++;
}; ?>
I was thinking about something like:我在想类似的事情:
$background_image = $banner['background_image']
if( wp_is_mobile() ) {
$background_image = $banner['background_image][sizes]['some_smaller_size_here'];
}
Thoughts?想法?
My hunch was correct.我的预感是正确的。 I first started by adding a new image size that would fit my needs:
add_image_size('home_page_banner', 800, 533);
我首先添加了一个适合我需要的新图像大小:
add_image_size('home_page_banner', 800, 533);
Then I re-wrote my conditionals like so:然后我像这样重写了我的条件:
if (wp_is_mobile()) {
$background_image = $banner['background_image']['sizes']['home_page_banner']; //returns url
} else {
$background_image = $banner['background_image']['url']; // returns url
}
Lastly, I re-wrote my echo statement to this:最后,我将我的回声语句重写为:
echo '<div class="home-page-banner grayscale" style="background-image: url(' . esc_url($background_image) . '); ">';
Now I can use a 1600px background image on desktop, and a 800px wide image on mobile.现在我可以在桌面上使用 1600 像素的背景图像,在移动设备上使用 800 像素宽的图像。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.