Home › Forums › ACF PRO › Delete media when clicking on remove button of file field › Reply To: Delete media when clicking on remove button of file field
There are a couple of options.
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.
Another way that this could be done is to add custom JavaScript to ACF and add an action to the remove button that fires an AJAX request to delete the file. This would be the best solution, but also the hardest to accomplish.
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.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.