如何通过SKU标识使用WooCommerce REST API更新产品
解决方案
你的代码核心问题是直接用wp_remote_post请求带SKU查询参数的URL,这会尝试创建新产品而非更新目标站点中匹配SKU的现有产品。正确流程应该是先通过SKU查询目标站点的产品ID,再用PUT请求更新该产品。
以下是修正后的完整代码:
add_action( 'woocommerce_update_product', 'sync_product_to_staging_by_sku', 10, 1 ); function sync_product_to_staging_by_sku( $product_id ) { // 获取当前生产站点的产品对象 $product = wc_get_product( $product_id ); if ( ! $product ) return; $product_sku = $product->get_sku(); if ( empty( $product_sku ) ) return; // 无SKU的产品跳过同步 // Staging站点的API凭证与基础URL $staging_ck = 'ck_xxxx'; $staging_cs = 'cs_xxxx'; $staging_base_url = 'https://web.com/wp-json/wc/v3/products'; // 第一步:通过SKU查询Staging站点的对应产品ID $search_url = add_query_arg( array( 'sku' => $product_sku, 'consumer_key' => $staging_ck, 'consumer_secret' => $staging_cs ), $staging_base_url ); $search_response = wp_remote_get( $search_url, array( 'timeout' => 30 ) ); if ( is_wp_error( $search_response ) ) return; $search_body = json_decode( wp_remote_retrieve_body( $search_response ), true ); if ( empty( $search_body ) || ! is_array( $search_body ) ) return; // 未找到匹配SKU的产品 $staging_product_id = $search_body[0]['id']; // 第二步:构建要更新的产品数据 $update_data = array( 'name' => $product->get_name(), 'status' => 'private', 'regular_price' => $product->get_regular_price(), 'sale_price' => $product->get_sale_price(), 'description' => $product->get_description(), 'sku' => $product_sku, 'weight' => $product->get_weight(), 'manage_stock' => true, 'stock_quantity' => 10, ); // 第三步:用PUT请求更新Staging站点的对应产品 $update_url = sprintf( '%s/%d', $staging_base_url, $staging_product_id ); $update_url = add_query_arg( array( 'consumer_key' => $staging_ck, 'consumer_secret' => $staging_cs ), $update_url ); $update_response = wp_remote_request( $update_url, array( 'method' => 'PUT', 'headers' => array( 'Content-Type' => 'application/json' ), 'timeout' => 30, 'body' => json_encode( $update_data ), ) ); // 可选:添加日志记录,方便排查同步问题 // if ( is_wp_error( $update_response ) ) { // error_log( '产品同步失败:' . $update_response->get_error_message() ); // } else { // error_log( '产品同步成功,Staging产品ID:' . $staging_product_id ); // } }
关键修正说明
- 查询匹配产品ID:使用
wp_remote_get请求带SKU参数的API接口,获取目标站点中对应SKU的产品ID(返回结果为数组,取第一个匹配项即可)。 - 使用PUT请求更新:WooCommerce REST API规定,更新现有产品必须使用
PUT方法,请求URL需指向具体的产品ID,而POST方法仅用于创建新产品。 - 参数安全处理:用
add_query_arg构建URL,避免手动拼接导致的URL编码错误。 - 错误防护:增加了产品对象、SKU有效性、查询结果的判断逻辑,避免无效请求触发报错。
额外优化建议
- 不要硬编码API凭证,建议将其存储在
wp-config.php中:
之后在函数中直接调用常量即可。define( 'STAGING_WC_CK', 'ck_xxxx' ); define( 'STAGING_WC_CS', 'cs_xxxx' ); - 对于大产品数据或批量同步场景,建议加入异步处理(比如WP Cron),避免阻塞产品保存流程。
- 保留日志记录逻辑,方便快速定位同步失败的原因。
内容的提问来源于stack exchange,提问作者Lubo Masura
相关产品推荐
相关产品推荐

