X

Remove featured image when deleting post with wp_delete_attachment

In a recent project I needed to create posts and upload images from the front end as featured image. So as a result I also needed to remove these attachments when people deleted the posts. Otherwise we would have a lot of orphan images using up lots of precious space in our WordPress Media Library. Adding this snippet to the functions.php of your WordPress theme will remove featured images when you delete a post using before_delete_post hook. You will want to be careful with this snippet if you attach the same image to multiple posts as the featured image so keep that in mind. One other thing to remember is that media library items are deleted when the post is deleted not put into trash so you will need to fully delete the post to see the image removed.


Code Snippet:


add_action( 'before_delete_post', 'wps_remove_attachment_with_post', 10 );
function wps_remove_attachment_with_post($post_id)
{

if(has_post_thumbnail( $post_id ))
{
$attachment_id = get_post_thumbnail_id( $post_id );
wp_delete_attachment($attachment_id, true);
}

}

Comments  Leave a Reply

  1. Excellent, been looking for it.. Thank you so much.

  2. Hey how do we add this type of <3 Recommended Button in our wordpress posts.

  3. Hi
    Thanks it’s very usefull and it also delete all the generated thumbnails 🙂 but I’m also look for the same snippet BUT to delete all WP image gallery (included generated thumbnails) that are attached to a post. Any idea?
    Thanks

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!