-1

I create, update and delete products using Woocommerce RestAPI, specifically this method:

$woocommerce->post('products/batch', $data);

After this method connected images remain in the server and db.

So, this is the code which deletes connected images from the database and server folder after deleting the post (product):

$this->woocommerce->post('products/batch', $data);
$this->deleteImages($data['delete']); // [ $key => $id_post ]

private function deleteImages($productIds)
    {
        foreach ( $productIds as $productId ) {
            $args = [
                //'numberposts' => 2,
                'order' => 'ASC',
                'post_mime_type' => 'image',
                'post_parent' => (int) $productId,
                'post_status' => 'inherit',
                'post_type' => 'attachment',
            ];
            $child = get_children($args);

            foreach ($child as $id => $item) {
                $pathImg = str_replace(get_site_url(), ABSPATH, $item->guid);
                $pathParts = pathinfo($pathImg);
                $extension =  end(explode(".", $pathImg));
                $imgWithoutExtension = $pathParts['dirname'] . '/' . basename($pathParts['basename'], '.' . $extension);

                array_map('unlink', glob($imgWithoutExtension . '*')); //ex:[img.jpg, img1x1.jpg, img5x5.jpg, img.gif]
                wp_delete_post($id);
            }
        }
    }

Is it normal realization? How would you edit this code?

1
  • featured image ids are stored in post meta not post parent column of posts table.
    – Joel M
    Commented Feb 22, 2020 at 6:41

1 Answer 1

0

Looking at @obmerks answer on https://stackoverflow.com/questions/12997698/delete-images-after-post you can simplify it with this:

foreach ( $productIds as $productId ) {
  $child_atts = $wpdb->get_col("SELECT ID FROM {$wpdb->posts} WHERE post_parent = $productId AND post_type = 'attachment'");
  foreach ( $child_atts as $id ) wp_delete_attachment($id,true);
}

Note: as per documentation https://codex.wordpress.org/Function_Reference/wp_delete_attachment set the second parameter to true to force delete the attachment, otherwise it goes to trash.

4
  • wp_delete_attachment($id,true) deletes files from server?
    – Zhi V
    Commented Nov 24, 2017 at 14:36
  • Yes, and also auto-generated thumbnails. Remember to use "true" for second parameter. Commented Nov 24, 2017 at 14:55
  • Thank you, I just reinvented the weel. But without connection to DB, it looks better. Just $child_atts = get_children($args)
    – Zhi V
    Commented Nov 24, 2017 at 15:15
  • My pleasure :-) Commented Nov 25, 2017 at 16:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.