How use custom image size + ACF + background image

admin2025-06-04  8

How to get the URL from an image with custom image size to use as a background-image from AFC?

Register size in functions.php:

add_theme_support( 'post-thumbnails' );
add_image_size( 'homepage-thumb', 220, 180 ); // Soft Crop

Display image with custom size (named: customsize) on page with ACF:

<?php $image = get_field('image_field'); ?>
<img src="<?php echo $image['sizes']['customsize']; ?> />

But how to display image as background image with ACF?:

<?php $image = get_field('image_field'); ?>             
<div style="background-image: url(<?php $image['url'] ?>)" /></div>

How to get the URL from an image with custom image size to use as a background-image from AFC?

Register size in functions.php:

add_theme_support( 'post-thumbnails' );
add_image_size( 'homepage-thumb', 220, 180 ); // Soft Crop

Display image with custom size (named: customsize) on page with ACF:

<?php $image = get_field('image_field'); ?>
<img src="<?php echo $image['sizes']['customsize']; ?> />

But how to display image as background image with ACF?:

<?php $image = get_field('image_field'); ?>             
<div style="background-image: url(<?php $image['url'] ?>)" /></div>
Share Improve this question asked Jan 2, 2019 at 18:08 LudoLudo 612 silver badges11 bronze badges 1
  • what is the HTML output when you run your last snippet? – RiddleMeThis Commented Jan 2, 2019 at 18:14
Add a comment  | 

1 Answer 1

Reset to default 1

First off, this code...

<img src="<?php echo $image['sizes']['customsize']; ?> />

is missing the end quote, it should be...

<img src="<?php echo $image['sizes']['customsize']; ?>" />

You can use that same php to output the URL for the background size.

<div style="height: 300px; width: 300px; background-image: url(<?php echo $company_logo['sizes']['customsize']; ?>)" /></div>

Tested and works.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749050294a315931.html

最新回复(0)