Search code examples
phpwordpressadvanced-custom-fields

ACF & Wordpress Media Library


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 class="hero-content" 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 class="hero-content" 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.


Solution

  • 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 ?>" onerror="this.onerror=null;this.src='https://www.domain-name.co.uk/fallback-folder/missing-placeholder-img.jpg';">