Remove Featured Image When Deleting a Post with wp_delete_attachment

When you delete any posts or pages, the featured images that you’ve attached to them remain on your website. If you want to remove the featured image attachments as well while deleting a post or page, then add this snippet to your functions.php file.

2 things to keep in mind:

  • If you attach the same featured image to multiple posts, then permanently deleting any of those posts will delete the featured image as well.
  • The images will only be removed when you permanently delete the post from trash.

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?

    1. Yes. I’m looking for it too, not only delete the feature image but delete the feature images generated thumbnails. Have you found anything?

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!