Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Woocommerce when deleting a product, automatically also delete the product gallery and product image

I was trying the following:

when a product page gets deleted (permanently), it should also delete the: product gallery and product image which are attached to the post.

I tried the solution i found on: https://wordpress.stackexchange.com/questions/109793/delete-associated-media-upon-page-deletion

But it didn't work out for me.

like image 914
Matthias Wegtun Avatar asked Oct 20 '25 13:10

Matthias Wegtun


2 Answers

Although this is an old question, I will leave it here in case someone will be looking for it in the future.

Since you want to delete product images, you may try these neat and handy woocommerce functions to get attachments ids.

Something like this:

add_action( 'before_delete_post', 'delete_product_images', 10, 1 );

function delete_product_images( $post_id )
{
    $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 ) ) {
        wp_delete_post( $featured_image_id );
    }

    if( !empty( $image_galleries_id ) ) {
        foreach( $image_galleries_id as $single_image_id ) {
            wp_delete_post( $single_image_id );
        }
    }
}

Works fine for me.

like image 129
v-khast Avatar answered Oct 23 '25 03:10

v-khast


add_action("before_delete_post","wdm_delete_post_images",10,1);

function wdm_delete_post_images($post_id)
{
 global $wpdb;
          $args = array(
                'post_parent' => $post_id,
                'post_type'   => 'attachment', 
                'numberposts' => -1,
                'post_status' => 'any' 
        ); 
        $childrens = get_children( $args);
        if($childrens):
            foreach($childrens as $attachment):   
             wp_delete_attachment( $attachment->ID, true ); 
             $wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE post_id = ".$attachment->ID);
             wp_delete_post($attachment->ID,true ); 
            endforeach;

        endif;
}
like image 41
Alex Avatar answered Oct 23 '25 03:10

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!