et-open-submissions-featured-image

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.

Share This Post

Related Post

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

      1. Hi,

        Thanks for your quick response!

        I inserted the code in the following path:
        /wp-content/themes/poza-child/functions.php

        I use Dokan multivendor plugin and Poza theme.
        The file was empty before.
        It still doesn’t work… 🙁

        What did I do wrong..?

    1. Hi Adi,

      This is a very powerful code for Dokan users by Nazmul, however; I found this hook worked for featured images, but not for gallery images for some reason so I modified it slightly and it works. You may want to give it a try too:

      I believe Nazmul may be changing the code to make it work for all the product images rather than just individual vendors so that it still works when the same product is sold by multiple vendors because in that case only the first vendor who listed that product will have its images and rest of the vendors will loose images attached to it, if this can be archived this will become the most perfect solution 🙂

      CODE:

      add_action( ‘before_delete_post’, function( $id ) {
      $product = wc_get_product( $id );
      if ( ! $product ) {
      return;
      }
      $product_thum_id_holder = [];
      $gallery_image_id_holder = [];
      $thum_id = get_post_thumbnail_id( $product->get_id() );
      $vendor = dokan()->vendor->get( dokan_get_current_user_id() );
      if ( ! $vendor instanceof Dokan_Vendor || $vendor->get_id() === 0 ) {
      return;
      }
      $products = $vendor->get_products();
      if ( empty( $products->posts ) ) {
      return;
      }
      foreach ( $products->posts as $post ) {
      $product_id = ! empty( $post->ID ) ? $post->ID : 0;
      if ( ! $product_id ) {
      continue;
      }
      if ( intval( $product_id ) !== intval( $id ) ) {
      array_push( $product_thum_id_holder, get_post_thumbnail_id( $product_id ) );
      $wc_product = wc_get_product( $product_id );
      $gallery_image_ids = $wc_product->get_gallery_image_ids();
      if ( empty( $gallery_image_ids ) ) {
      continue;
      }
      foreach ( $gallery_image_ids as $gallery_image_id ) {
      array_push( $gallery_image_id_holder, $gallery_image_id );
      }
      }
      }
      if ( ! in_array( $thum_id, $product_thum_id_holder ) && ! in_array( $thum_id, $gallery_image_id_holder ) ) {

      //Added:
      wp_delete_attachment( $thum_id, true );
      if ( empty( $thum_id ) ) {
      return;

      }
      $gallery_image_ids = $product->get_gallery_image_ids();
      if ( empty( $gallery_image_ids ) ) {
      return;

      }
      foreach ( $gallery_image_ids as $gallery_image_id ) {
      wp_delete_attachment( $gallery_image_id, true );}
      }
      } );

      Thanks

      1. Hi, thank you all!

        I think that the problem is, that in Dokan, when a seller upload a product with images, the images are not associated with the product, so, when you deleting the product the images remain in the server.

        The code works perfectly when the admin uploads a product.

        Do you have a solution for that?

        1. Hello Adi,

          I don’t think so because I checked from the frontend too. Even Syed tried it and worked fine. Kindly upload a new product with a new image then try 🙂

        2. Hi Adi, you need to make sure the images attached to the product you’re deleting is not attached to any other product because that’s the whole point, so as Nayem says try a unique featured and gallery image that is not used with any other product and then it should work fine.

          The code will first check if the gallery or featured image is not used for any other product from the vendor’s own media library then attempt to delete the images otherwise it won’t delete any image, so for instance if you have a product with a unique featured image but the gallery image attached is being used for other products then upon deleting such a product you will see the featured image will be deleted while the gallery image remains in the media library. It works from both back and front end for me.

  1. Hello Nayem,

    I know you must be a busy man, but when you get time can you make the code work in a manner so it checks if images are not used by any vendor before deleting rather than individual vendors so that it can work with single product multiple vendor senario?

    Many thanks,

    1. Hi Nayem,

      I actually realized that issue is not specific to Dokan, even WooCommerce does not show images as attached when added from back end , so if Dokan can sort that issue then it would be great but it is wordpress in general that does that I guess.

  2. Hello,

    Can you guys tell me how you are processing the code? You have to add the code and then upload the image to your product and then try deleting it.

  3. Hi Nayem,

    I haven’t tested the function yet but noticed a warning while loading the Shop page. Too quick too read and doesn’t show with debug enabled but the source code shows this;

    Use of undefined constant ‘before_delete_post’ – assumed ‘‘before_delete_post’’ (this will throw an Error in a future version of PHP) in /home/xxxxxx/xxxxxxx/wp-content/themes/woodmart-child/functions.php on line 56

    (currently PHP 7.3)

    Note: I’ve removed the code entirely for now.

    Cheers,
    Andre

  4. Hi, guys, the code worked for me (I am not using Dokan), only some pushed printful products that I needed to be deleted and it worked just fine.

  5. hello,I not used the dokan theme,and the code did not work for me!!I just want to delet the out of stock products with their images

  6. Hi! I have tested the code, but after that, when I add a product, the popup of the product does not dissappear, I have to close it manually. And then, when I delete a product, I get a blank page and I have to update the page to go back to the products page.

  7. Hi,

    Excellent hook, works perfect, congratulations.

    I would like to know how I could get it to delete the .webp images as well? I only delete the .jpg images

    Thanks

  8. I got this same error:

    “Use of undefined constant ‘before_delete_post’ – assumed ‘‘before_delete_post’’ (this will throw an Error in a future version of PHP) in /home/xxxxxx/xxxxxxx/wp-content/themes/woodmart-child/functions.php on line 56”

  9. Hello,

    Our site closed down after entering the code. We enter the code xxxxxxx/wp-content/themes/woodmart-child/functions.php on line 9.
    Do you know if we enter the code at the end (last line) of the functions.php?

  10. Tested with:
    Dokan v3.2.6, WooCommerce-Version: 5.3.0, WordPress-Version: 5.7.2
    It works without any errors, perfectly.

  11. I tried it, it works great with Dokan 3.2.8 & Dokan Pro 3.3.2. This code solved one of my problems. Thank you so much.

    Now I’m looking for a solution to another problem related to Dokan:

    When a seller upload a product with images, the images are not associated with the product. This complicates Media Library management.

    Actually better; A solution would be to add Product ID or SKU to image tags when adding products. So it would be easier to figure out which product the pictures belong to.

  12. I tried this code and works perfectly.

    Is there a way to be able to delete the files (PDF, ZIP, etc that was uploaded by the vendor) when deleting a product in Dokan?

  13. Hello to all,

    I would like to ask how can I delete photos of products which I deleted from trash woocommerce?

    Any idea?

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: