简体   繁体   English

ACF & Wordpress 媒体库

[英]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.我有一个 ACF“选项页面”,里面有一个占位符图像,如果客户错误地从帖子/页面中删除了图像,我可以回退。 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.谢谢。

You can use attachment_url_to_postid .您可以使用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.使用此 function 您可以从图像 url 获取帖子 ID。如果帖子 ID 不存在,则用户之前删除了附件。 so based on the result of this function you can actually test of attachment is deleted or not and use placeholder instead.因此,根据这个 function 的结果,您实际上可以测试附件是否被删除并改用占位符。

I've solved this issue using onerror for anyone with similar concerns.对于有类似问题的任何人,我已经使用onerror解决了这个问题。

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';">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM