woocommerce offtopic - How to delete images from database with product

admin2025-01-07  4

I use WooCommerce REST API for updating/creating/deleting products. When I try to delete a product using $woocommerce->post('products/batch'), an image connected with a product is not deleting from the DB and filesystem. It takes up unnecessary space on the server.

What is the best way to resolve this problem?

I use WooCommerce REST API for updating/creating/deleting products. When I try to delete a product using $woocommerce->post('products/batch'), an image connected with a product is not deleting from the DB and filesystem. It takes up unnecessary space on the server.

What is the best way to resolve this problem?

Share Improve this question edited May 18, 2019 at 1:40 butlerblog 5,0713 gold badges26 silver badges42 bronze badges asked Nov 23, 2017 at 12:41 Zhi VZhi V 2211 gold badge2 silver badges13 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 0

I'd first get the attachment ID and with the attachment ID you could use wp_delete_attachment($att_id)

you can try this

$all_posts = get_posts(array(
    'numberposts' => - 1,
    'post_status' => 'any',
    'post_type' => get_post_types('', 'names') ,
));

foreach($all_posts as $all_post) {
    delete_post_media($all_post->ID);
}

function delete_post_media($post_id)
{
    if (!isset($post_id)) return;
    elseif ($post_id == 0) return;
    elseif (is_array($post_id)) return;
    else {
            $attachments = get_posts(array(
                    'post_type' => 'attachment',
                    'posts_per_page' => - 1,
                    'post_status' => 'any',
                    'post_parent' => $post_id
            ));
            foreach($attachments as $attachment) {
                    if (false === wp_delete_attachment($attachment->ID)) {

                            // Log failure to delete attachment.

                    }
            }
    }
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736252534a53.html

最新回复(0)