I have created a ACF custom field of images connected to my custom post type. However, if no image is selected it will retrieve a default image from the media library.
To display images, if check get_field(‘box_image’) is empty/null, default to selected image with get_theme_file_uri(‘/assets/images/img.jpg’); function.
All images are displayed correctly below, as I have set add_image_size of 250×180, but how can I make the default image (second) render to 250×180 as well ?
Here is my code:
<?php
$image = get_field('box_image');
//$size = ['sizes']['box_bg_image'];
if (!empty($image)) { ?>
<img src="<?php echo esc_url($image['sizes']['box_bg_image']); ?>" />
<?php } else { ?>
<img src="<?php echo get_theme_file_uri('/assets/images/img.jpg'); ?>" />
<?php } ?>
functions.php:
add_image_size('box_bg_image', 250, 180, array('center', 'center'));
css:
.bg-image img { opacity: 0.4; width: 100%; vertical-align: top; transition: opacity 0.35s; }
I have tried these similar outputs, but I get errors:
<img src="<?php echo get_theme_file_uri('/assets/images/city.jpg')['sizes']['box_bg_image']; ?>" />
<img src="<?php echo get_theme_file_uri('/assets/images/city.jpg'), $size; ?>" />
I have tried scouring the net to see if its possible to set the size for get_theme_file_uri image, but I cant seem to find a solution.
Should I be using a different function to assign the size?
EDIT:
I have come up with this, although I am not 100% its the right way of doing it.:
<img src="<?php echo wp_get_attachment_image_src(158, 'box_bg_image')[0]; ?>" />
I know the get_theme_file_uri() retrieves one parameter and the wp_get_attachment_image_src() can take in multiple parameters, so I would think this would be one way of selecting a default image?
If anyone has other suggestions, please let me know.
2
Answers
Use
object-fit
property for that purposeHere are some and can refer to this for more info abut
object-fit
:contain : The image keeps its aspect ratio, but is resized to fit within the given dimension
cover : The image keeps its aspect ratio and fills the given dimension. The image will be clipped to fit
none : The image is not resized
scale-down : the image is scaled down to the smallest version of none or contain
try this instead