You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用WooCommerce REST API删除图片时遇401权限错误求助

问题:WooCommerce REST API删除商品图片返回401权限错误

尝试通过WooCommerce REST API删除商品及关联图片时,商品可正常删除,但关联图片无法删除。单独调用删除图片接口时返回以下错误:

{"code":"rest_cannot_delete","message":"Sorry, you are not allowed to delete this post.","data":{"status":401}}

已尝试以下操作但问题仍未解决:

  • 创建具备读写权限的新API密钥
  • 使用 staging 站点(子域名)的管理员账号生成API密钥

当前使用的代码:

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;
    }
}

可能的解决方案

1. 确认API密钥对应角色的媒体删除权限

WooCommerce的API读写权限仅覆盖商品、订单等WooCommerce资源,删除媒体属于WordPress核心REST API操作,需确保API密钥绑定的用户角色拥有删除媒体的权限:

  • 登录WordPress后台,进入「用户」页面,找到生成API密钥的管理员账号,确认角色为管理员(默认管理员拥有delete_others_media、delete_private_media、delete_published_media权限)。
  • 若使用自定义角色,需手动添加上述媒体删除权限。

2. 改用WooCommerce商品更新接口先解除图片关联

直接删除媒体可能因关联关系或权限受限,可先通过WooCommerce API清空商品的图片数组,解除关联后再尝试删除媒体:

function remove_and_delete_product_images($product_id) {
    $woocommerce_url = 'https://staging.website.com';
    $consumer_key = '*consumer_key*';
    $consumer_secret = '*consumer_secret*';

    // 第一步:清空商品关联的图片
    $update_url = $woocommerce_url . '/wp-json/wc/v3/products/' . $product_id . '?force=true';
    $update_data = json_encode(['images' => []]);

    $ch = curl_init($update_url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Basic ' . base64_encode($consumer_key . ':' . $consumer_secret)
    ]);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
    curl_setopt($ch, CURLOPT_POSTFIELDS, $update_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $update_response = curl_exec($ch);
    $update_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($update_status !== 200) {
        error_log("Failed to clear product images: " . $update_response);
        return false;
    }

    // 第二步:获取原图片ID并删除媒体文件
    $product = json_decode($update_response, true);
    if (!empty($product['images'])) {
        $image_ids = array_column($product['images'], 'id');
        foreach ($image_ids as $image_id) {
            $delete_url = $woocommerce_url . '/wp-json/wp/v2/media/' . $image_id . '?force=true';
            $ch = curl_init($delete_url);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                '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);
            curl_close($ch);
            error_log("Deleted media ID $image_id: " . $delete_response);
        }
    }

    return true;
}

3. 排查安全插件的REST API拦截

部分安全插件(如Wordfence、iThemes Security)会限制REST API的媒体操作:

  • 临时禁用安全插件,测试是否能正常删除图片,确认是否为插件拦截。
  • 若为插件导致,在插件设置中添加允许管理员角色删除媒体的规则。

4. 检查媒体文件的上传者归属

如果目标图片是由其他用户上传的,当前管理员账号可能因权限限制无法删除:

  • 进入WordPress媒体库,查看目标图片的「上传者」是否为API密钥对应的管理员账号。
  • 若上传者是其他用户,确保当前管理员拥有delete_others_media权限(管理员默认拥有,若被自定义角色修改需恢复)。

5. 验证staging站点的版本兼容性

确认staging站点的WordPress、WooCommerce版本与生产站点一致,避免版本差异导致的API兼容性问题。


内容的提问来源于stack exchange,提问作者Gabiru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 23:16:03