On my site I have multiple authors, who can add/edit/delete custom posts and upload (attach) images to those posts. The problem is – when they delete their posts, attachments stay on the server. So, I would like to get rid of all files attached to the post when it gets deleted. Can anyone share and example how it’s done?
Leave a Reply
You must be logged in to post a comment.
WP does not do this by default since there is no guarantee that attachment isn’t still being used by some other post.
Basic logic would be to hook into
delete_post
, query for child attachments and runwp_delete_attachment()
on each.I did quick search in plugin repository and came up with tiny plugin that does just that (seems unmaintained so test before use) – Post Data Delete Advanced.
I wrote the following function that uses the logic suggested by @rarst in his answer.
IMPORTANT: Keep in mind it will only be called when the posts are permanently deleted from the trash! If you want to change this behaviour, include the following line in your
wp-config.php
file:(From the Codex)
Expanding on other answers here for use with only a specific post type.
This will delete all attached media when a post is permanently deleted.
Any one still looking for a simple solution then try the following plugin it works with normal post/page, and custom post types – Delete Post with Attachments