D
D
DMax9212018-12-11 10:52:33
WordPress
DMax921, 2018-12-11 10:52:33

How to delete a product along with images?

Hello, friends!
Today I noticed such an unpleasant thing.
I deleted 10 products, and noticed that the images of these products remained in the library, why are they not deleted along with the product?
Is there a plugin that would solve this problem?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex, 2018-12-11
@DMax921

Well, something like this: we hang on the post deletion event - search for all attached images and delete them one by one

<?php
add_action('before_delete_post', 'wps_remove_attachment_with_post', 10);
function wps_remove_attachment_with_post($post_id)
{
    // We check if the global post type isn't ours and just return
    global $post_type;
    if ($post_type != 'my_product_post_type')
        return;
    
    $media = get_attached_media('image', $post_id);
    foreach ($media as $image) {
        wp_delete_attachment($image->ID, true);
    }
    
}
?>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question