Home > Back-end >  ACF & Wordpress Media Library
ACF & Wordpress Media Library

Time:03-16

I've got an ACF 'options page' with a placeholder image within, to fall back to if a client removes the image from the post/page by mistake. And I'm using the following code to handle this situation happening.

<?php
// Variables
$banner_image = get_field('banner_image');   
$fallback_banner_image = get_field('fallback_image', 'options');
?>

<?php if ( $banner_image ): { ?>

<img  src="<?php echo esc_url( $banner_image_src[0] ); ?>" srcset="<?php echo esc_attr( $banner_image_srcset ); ?>" sizes="100vw" alt="<?php echo $banner_image_alt_text ?>">

<?php } elseif ( empty( $banner_image ) ): { ?>
   
<img  src="<?php echo esc_url( $fallback_banner_image_src[0] ); ?>" srcset="<?php echo esc_attr( $fallback_banner_image_srcset ); ?>" sizes="100vw" alt="<?php echo $fallback_banner_image_alt_text ?>">

<?php } endif; ?>

This works fine once pages or posts are saved.

However

The issue I have is if the page/post has been previously saved with an image and then a user deletes the image from the Media Library directly, the field doesnt become 'empty' so the content just disappears, rather than falling back to the placeholder image that I would like it to.

Any advice on how to handle images directly removed from the Media Library?

Thanks.

CodePudding user response:

You can use attachment_url_to_postid. Using this function you can get post id from image url. if post id is not exists , user deleted the attachment before. so based on the result of this function you can actually test of attachment is deleted or not and use placeholder instead.

CodePudding user response:

I've solved this issue using onerror for anyone with similar concerns.

I placed a folder, with a simple light grey placeholder image in it, in the root of my theme directory, so it can never be deleted by a user.

Then added the following to the end of my image tag. Seems to work perfectly when ever the media library images are removed by mistake.

<img src="<?php echo esc_url( $image_src[0] ); ?>" srcset="<?php echo esc_attr( $image_srcset ); ?>" sizes="(min-width: 1050px) 25vw, (min-width: 750px) 33.333vw, (min-width: 500px) 50vw, 100vw" alt="<?php echo $image_alt_text ?>" one rror="this.onerror=null;this.src='https://www.domain-name.co.uk/fallback-folder/missing-placeholder-img.jpg';">
  • Related