X

How to Remove Featured Image When Deleting a Post with wp_delete_attachment

Snippets by IsItWP

Are you looking for a way to remove featured image when deleting a post with wp_delete_attachment? While there’s probably a plugin for this, we have created a quick code snippet that you can use to remove featured image when deleting a post in WordPress.

When you delete a post or page, the featured image that you’ve attached to it will remain there on your website. If you want to remove the featured image attachments as well while deleting the post or page, then keep in mind:

  • If the same featured image is attached 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.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

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);
	}

}

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly add code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 7 best WordPress GDPR plugins to create a GDPR compliant site and how to create a WordPress donation form.

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

    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?

    2. I want this too, remove all the image related to the post, like insert image for content inside through media insert.

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!
[60% OFF Today!]
[60% OFF Today!]
[10% OFF Today!]
[10% OFF Today!]
[50% OFF Today!]
[50% OFF Today!]