I have a file field which is used to upload pdf files.
When I edit a page and use the field to upload a file, it displays the filename, title and size. When I hover over this field there is a edit button and a remove button.
When I click the remove button, the file disappears from the file field (and I can select a new file), but the file remains in WordPress media libary. How do I delete the file from the media libary when I click the remove button on the file field?
One way to do this is to create an acf/save_post action with a priority of < 10. In this action you can compare the old value in the field get_field('file_field') with the new value submitted $_POST['acf']['field_KEY'] and if they are different then use wp_delete_attachment() to delete the old file. This will only work after a post has been saved. So if someone adds a file and then changes their mind before saving then the file will not be deleted.
A variation of the above (still using an acf/save_post action) would be get all of the attachments for the post being saved https://stackoverflow.com/questions/42917812/how-to-get-all-attachments-for-a-wordpress-post. All files uploaded in an ACF field should be attached to the post. Then look in every field that is for an attachment (file, image, gallery) and get a list of the ones actually being used and delete the ones that are not. The flaw in this method is that you will not be able to detect files or images that are added in the WP editor or a WYSIWYG field and you’d end up deleting these.
There is another flaw with every method, you will not know if the same file has been used on another post. Deleting the file if it is used somewhere else will cause issues with wherever else it is used.
Viewing 2 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users