How to delete images when deleting a product in WooCommerce?

What is good for you can be unnecessary for others! That’s what I am seeing over the last few years even in plugin/software functionalities. Today I am going to write about the uploaded image for a product through WooCommerce or any multivendor plugin works on WooCommerce like Dokan.

When you are running a multivendor marketplace or an e-commerce store with WooCommerce then you are uploading tons of products with thousands of images. When you are uploading lots of products definitely you are deleting a huge number of products due to some reasons. After deleting every product when you check your media library you are seeing all those images which were used for your deleted products.

WordPress does not delete media upon deleting a post because Media Library built to re-use images/files to one or multiple posts. That’s really great for me because I use same feature image on multiple post 😛

Now, when it’s a multivendor website it is really hard to keep track of each and every vendor uploaded media. So, your vendor might be uploading 100 products per day and deleting a good number of products. Their product images are reducing your server space which is not good for a marketplace/e-commerce owner.

In that case, most of them will love to delete all the featured image and gallery image if the user/vendor delete any product.

I know you will ask "What if you are using same images on multiple posts?"

Yes, I will definitely provide a good solution to save your left and right hand 😀

Deleting attached images upon deleting a post/product

WordPress is amazing because it allows you to modify your own wish. I will use that facility to apply my solution. Yeas, you got me correctly!

I am going to use a hook which is `before_delete_post` and you can read details about this hook here.

Now, open your child theme’s functions.php file and paste the below code-

After saving the functions.php now permanently delete a product. You will see the magic. Let’s try and put your feedback in a comment.

2 thoughts on “How to delete images when deleting a product in WooCommerce?

Leave a Reply

Your email address will not be published. Required fields are marked *