我使用Woocommerce RestAPI创建、更新和删除产品,特别是使用以下方法:
$woocommerce->post(\'products/batch\', $data);
使用此方法后,连接的图像将保留在服务器和数据库中。
因此,这是删除帖子(产品)后从数据库和服务器文件夹中删除连接图像的代码:
$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);
}
}
}
这是正常的实现吗?您将如何编辑此代码?