AI Verified

Name

Delete Woocommerce images after deleting product

About

Automatically Delete WooCommerce Images After Deleting a Product. If you use the same image of multiple products the image will not be deleted for those

Language

PHP

Rating

Voted: 5 by 9 user(s)

How to Setup Snippet

Just add the snippet to Code snippets. Try and delete a product. All images will be deleted including product gallery images

Codevault

George Snippet Library

Scroll down to see more snippets from this codevault.

Wordpress Compatability

The author has indicated that this snippet is compatable up to wordpress version: 6.1

Our AI bot has checked this snippet is compatable up to wordpress version: 6.1

Code Snippet Plugin Sync

Free & Pro

Download this snippet by clicking the download button, then head over to the Code Snippet Plugin settings in your wordpress admin dashboard, select the import menu then upload this file to import into your wordpress site.

Pro Only (Coming Soon)

You will be able to click a button and sync this snippet to your wordpress site automatically and from your dashboard manage all code snippets across all your wordpress sites that have the Code Snippets Pro plugin installed.

History

Last modified:

13/06/2024

Important Note

This snippet has the following status:

AI Verified

This snippet has been tested by our AI bot, see any comments below.

AI Bot Comments:

Found 0 vulnerabilities

Delete Woocommerce images after deleting product

 
                    
1// Automatically Delete Woocommerce Images After Deleting a Product
2add_action( 'before_delete_post', 'delete_product_images', 10, 1 );
3 
4function delete_product_images( $post_id ) {
5 // Check if user has the capability to delete products
6 if ( !current_user_can( 'delete_products' ) ) {
7 return;
8 }
9 $product = wc_get_product( $post_id );
10 
11 if ( !$product ) {
12 return;
13 }
14 
15 $featured_image_id = $product->get_image_id();
16 $image_galleries_id = $product->get_gallery_image_ids();
17 
18 if( !empty( $featured_image_id ) ) {
19 $is_featured_image_used = is_image_used( $featured_image_id, $post_id );
20 if ( !$is_featured_image_used ) {
21 wp_delete_attachment( $featured_image_id, true );
22 }
23 }
24 
25 if( !empty( $image_galleries_id ) ) {
26 foreach( $image_galleries_id as $single_image_id ) {
27 $is_image_used = is_image_used( $single_image_id, $post_id );
28 if ( !$is_image_used ) {
29 wp_delete_attachment( $single_image_id, true );
30 }
31 }
32 }
33}
34 
35function is_image_used( $image_id, $current_product_id ) {
36 $query = new WP_Query( array(
37 'post_type' => 'product',
38 'post_status' => 'publish',
39 'meta_query' => array(
40 'relation' => 'OR',
41 array(
42 'key' => '_thumbnail_id',
43 'value' => $image_id,
44 'compare' => '='
45 ),
46 array(
47 'key' => '_product_image_gallery',
48 'value' => '"'.$image_id.'"',
49 'compare' => 'LIKE'
50 )
51 ),
52 'post__not_in' => array( $current_product_id ),
53 'fields' => 'ids',
54 'posts_per_page' => -1
55 ) );
56 
57 return ( $query->have_posts() );
58}

5

Featured Snippet

Comments

  • IS

    1 year ago

    Awesome
  • GN

    1 year ago

    Glad you like it mate. It's insane to me that it's not default behavior 
  • NS

    1 year ago

    Just Awesome, This is insanely good :)  Can you please create your magic to delete images of previously deleted products? :)
    
    This deletes the images after adding the snippet, but we already deleted so many products, and many images are there for no reason, Yes there are many plugins but none worked and deleting more than required.
    
    Thanks for this awesomeness :)
  • GN

    1 year ago

    @Niral Sura that is not possible since if you already deleted the product I can't think of a way the database would remember the product id so sorry
  • V

    1 year ago

    Thank you George. Amazing snippet
  • VR

    1 year ago

    Thank you! It's amazing. Is it possible to change the code so that images are also removed for those products that were removed using third-party solutions, for example, the bulk product removal plugin or the bulk product editing plugin, or using any integrations with woocommerce? 
  • GN

    1 year ago

    @Vladimir Rechnov when a product is deleted the id is gone so I would think there wouldn't be a way oi "remember" the ids of removed products
    
  • JP

    9 months ago

    Hi there,
    I was using this snippet, but I think there may be an issue with it.
    Can you please test the following and see if you get the same results?
    
    Create and publish a variable product with multiple variations, each with their own product image.
    Use the 'Copy to a new draft' to create a copy of the variable product.
    
    During the 'Copy to a new draft' process this snippet deletes all but the main product image, leaving all variations from the original product with no images.
    
    I use the 'Copy to a new draft' a lot as most of my products are very similar, so making a copy and doing minor changes is the fastest way to create new products.
    Unfortunately this issue makes the snippet completely unuseable, I'm just glad I spotted it relatively early and only had to reupload a few variable product images.
    
    If you're able to replicate the issue, do you think it would easy to fix?
    
    Thank you for your help!
  • GN

    9 months ago

    Hey Jon-Paul I will need to look into this as soon as I get a minute. As a note I have opened yoru issue on my github so I do forget to fix it. I will update the code as soon as I can replicate the issue and will update the code here. The way you will know i is updated is by looking at the version of the plugin in the repo it's currently version 1.0.0 when that changes it means I fixed it. It may not be today though to be honest. You can track the github issue at https://github.com/GeorgeWebDevCy/gn-product-and-image-remover/issues/1
  • JP

    9 months ago

    Hi George,
    Thank you for taking a look at this!
    I've subbed to the GitHub and look forward to seeing how you get on.
  • JP

    8 months ago

    Hi George,
    Thanks again for taking a look at this.
    I've retested and the error was mine.
    I was deleting the copied product variations so I could create new ones, and when doing this the images associated with the variations are deleted... which also deletes them from the original product.
  • GN

    8 months ago

    @Jon-Paul so you are confirming that the snippet is working as expected correct? I ask so I can close the issue on github too
    
    
  • GN

    8 months ago

    @Jon-Paul feedback is always appreciated. Thank you for using the snippet.
    
    
  • D

    5 months ago

    This works great, could you make it as a plugin that deletes all the products and images both from media tab and disk. I need it because, every day, I need to delete all the products from my Woocommerce, and then import new CSV. It is easy when there are ~1000 products, but, when there are more, it gets a bit difficult ;) Thanks
  • GN

    5 months ago

    Hey @Doole 
    
    I have this as a plugin on the repo https://wordpress.org/plugins/gn-product-and-image-remover/#:~:text=GN%20Product%20and%20Image%20Remover%20is%20a%20WordPress%20plugin%20designed,not%20used%20in%20other%20products.
    
    Skipping trash is bad practice but if you want to risk it then download the plugin replace the code in the file gn-product-and-image-remover.php with the below 
    <?php
    /**
     * GN Product and Image Remover
     *
     * @package      GNCYPRODUCTREMOVER
     * @author       George Nicolaou
     * @version      1.0.0
     *
     * @wordpress-plugin
     * Plugin Name:   GN Product and Image Remover
     * Plugin URI:    https://www.georgenicolaou.me/plugins/gn-product-and-image-remover
     * Description:   Allows you to delete WooCommerce images after deleting a product unless the image is used in another product.
     * Version:       1.0.0
     * Author:        George Nicolaou
     * Author URI:    https://www.georgenicolaou.me/
     * Text Domain:   gn-product-and-image-remover
     * Domain Path:   /languages
     */
    
    // Exit if accessed directly.
    if (!defined('ABSPATH'))
        exit;
    
    /**
     * HELPER COMMENT START
     *
     * This file contains the main information about the plugin.
     * It is used to register all components necessary to run the plugin.
     *
     * The comment above contains all information about the plugin 
     * that is used by WordPress to differentiate the plugin and register it properly.
     * It also contains further PHPDocs parameters for better documentation.
     *
     * The function GNCYPRODUCTA() is the main function that you will be able to 
     * use throughout your plugin to extend the logic. Further information
     * about that is available within the sub-classes.
     *
     * HELPER COMMENT END
     */
    
    // Plugin name
    define('GNCYPRODUCTREMOVER_NAME', 'GN Product and Image Remover');
    
    // Plugin version
    define('GNCYPRODUCTREMOVER_VERSION', '1.0.0');
    
    // Plugin Root File
    define('GNCYPRODUCTREMOVER_PLUGIN_FILE', __FILE__);
    
    // Plugin base
    define('GNCYPRODUCTREMOVER_PLUGIN_BASE', plugin_basename(GNCYPRODUCTREMOVER_PLUGIN_FILE));
    
    // Plugin Folder Path
    define('GNCYPRODUCTREMOVER_PLUGIN_DIR', plugin_dir_path(GNCYPRODUCTREMOVER_PLUGIN_FILE));
    
    // Plugin Folder URL
    define('GNCYPRODUCTREMOVER_PLUGIN_URL', plugin_dir_url(GNCYPRODUCTREMOVER_PLUGIN_FILE));
    
    /**
     * Load the main class for the core functionality
     */
    require_once GNCYPRODUCTREMOVER_PLUGIN_DIR . 'core/class-gn-product-and-image-remover.php';
    
    /**
     * The main function to load the only instance
     * of our master class.
     *
     * @author  George Nicolaou
     * @since   1.0.0
     * @return  object|Gn_Product_And_Image_Remover
     */
    
    // Check if WooCommerce is active
    function gncy_product_image_remover_check_for_woocommerce() {
        if (!class_exists('woocommerce')) {
            deactivate_plugins(plugin_basename(__FILE__));
            wp_die('Sorry, but this plugin requires WooCommerce to be installed and active. Please install WooCommerce and try again.');
        }
    }
    register_activation_hook(__FILE__, 'gncy_product_image_remover_check_for_woocommerce');
    
    // Load the main class for the core functionality
    require_once plugin_dir_path(__FILE__) . 'core/class-gn-product-and-image-remover.php';
    
    /**
     * The main function to load the only instance
     * of our master class.
     *
     * @return object|Gn_Product_And_Image_Remover
     */
    function GNCYPRODUCTREMOVER() {
        return Gn_Product_And_Image_Remover::instance();
    }
    
    add_action('before_delete_post', 'gncy_product_remover_delete_product_images', 10, 1);
    
    function gncy_product_remover_delete_product_images($post_id) {
        if ('product' !== get_post_type($post_id)) {
            return; // Only process WooCommerce products
        }
    
        $product = wc_get_product($post_id);
    
        if (!$product) {
            return;
        }
    
        $featured_image_id = $product->get_image_id();
        $image_galleries_id = $product->get_gallery_image_ids();
    
        if (!empty($featured_image_id)) {
            $is_featured_image_used = gncy_product_remover_is_image_used($featured_image_id, $post_id);
            if (!$is_featured_image_used) {
                wp_delete_attachment($featured_image_id, true);
            }
        }
    
        if (!empty($image_galleries_id)) {
            foreach ($image_galleries_id as $single_image_id) {
                $is_image_used = gncy_product_remover_is_image_used($single_image_id, $post_id);
                if (!$is_image_used) {
                    wp_delete_attachment($single_image_id, true);
                }
            }
        }
    }
    
    function gncy_product_remover_is_image_used($image_id, $current_product_id) {
        $query = new WP_Query(
            array(
                'post_type' => 'product',
                'post_status' => 'publish',
                'meta_query' => array(
                    'relation' => 'OR',
                    array(
                        'key' => '_thumbnail_id',
                        'value' => $image_id,
                        'compare' => '='
                    ),
                    array(
                        'key' => '_product_image_gallery',
                        'value' => $image_id,
                        'compare' => 'LIKE'
                    )
                ),
                'post__not_in' => array($current_product_id),
                'fields' => 'ids',
                'posts_per_page' => -1
            )
        );
    
        return ($query->have_posts());
    }
    
    // Override the default behavior of moving deleted products to trash
    add_filter('wp_trash_post_status', function ($post_status, $post) {
        if ($post->post_type === 'product') {
            return 'trash';
        }
        return $post_status;
    }, 10, 2);
    
    GNCYPRODUCTREMOVER();
    
    
    
    

Related Snippets

Please see some snippets below related to this snippet..

WooCommerce

AI Verified

1

WooCommerce Product Time Picker

Added: 1 year ago

Last Updated: 2 weeks ago

This snippet adds a product time picker to the single product template above the add to cart button and save the time picked against the product as meta data. Once a time is picked against the product...

WooCommerce

AI Verified

0

Prevent Spam Orders - WooCommerce Checkout

Added: 2 months ago

Last Updated: 2 months ago

WooCommerce

AI Verified

0

WooCommerce Change “Place Order” Button Text

Added: 1 year ago

Last Updated: 1 year ago

Sometimes, it may be necessary to change the default “Place Order” button text on the WooCommerce Checkout form. Some payment gateways overwrite this text anyway with their own text which is easy enou...

Other Snippets in this Codevault

These are some popular snippets from this users codevault..

WooCommerce

AI Verified

5

Delete Woocommerce images after deleting product

Added: 1 year ago

Last Updated: 1 month ago

Automatically Delete WooCommerce Images After Deleting a Product. If you use the same image of multiple products the image will not be deleted for those

WooCommerce

AI Verified

2

Add Alphabetical Sorting to Woocommerce

Added: 1 year ago

Last Updated: 2 weeks ago

Sorts products alphabetically in Woocommerce

WooCommerce

AI Verified

1

Remove categories from the shop and other pages in Woocommerce

Added: 1 year ago

Last Updated: 1 year ago

Remove any categories from WooCommerce frontend