So I am trying to delete the product along with the images via REST API but it deletes everything EXCEPT the images. I've tested it separately to delete an image but it give me this error:
{"code":"rest_cannot_delete","message":"Sorry, you are not allowed to delete this post.","data":{"status":401}}
I've tried new API keys with read/write, it does not work. I'm using an admin account in my subdomain(staging site) but I can't seem to find what causes the restriction to delete images.
I'm in a standstill with this problem for days. Can anyone help me?
This is my code:
function delete_product_image($product_id) {
$woocommerce_url = 'https://staging.website.com';
$consumer_key = '*consumer_key*';
$consumer_secret = '*consumer_secret*';
$get_product_url = $woocommerce_url . '/wp-json/wc/v3/products/' . $product_id;
error_log("URL: " . print_r($get_product_url, true));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $get_product_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: Basic ' . base64_encode($consumer_key . ':' . $consumer_secret)
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$product_response = curl_exec($ch);
curl_close($ch);
$product = json_decode($product_response, true);
if (isset($product['images']) && !empty($product['images'])) {
$image_ids = array_column($product['images'], 'id');
foreach ($image_ids as $image_id) {
$delete_image_url = $woocommerce_url . '/wp-json/wp/v2/media/' . $image_id . '?force=true';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $delete_image_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json',
'Authorization: Basic ' . base64_encode($consumer_key . ':' . $consumer_secret)
));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$delete_response = curl_exec($ch);
$delete_http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($delete_http_status == 200) {
error_log("Deleted Image with ID: $image_id");
} else {
error_log("Failed to delete image with ID: $image_id. Response: " . print_r($delete_response, true));
return false;
}
}
return true;
} else {
error_log("Product not found or no images to delete.");
return false;
}
}