
本文介绍如何通过自定义钩子实现两个 woocommerce 商品(包括变体)的常规价格自动同步,当任一商品价格手动修改时,另一商品价格实时更新,确保价格严格一致。
本文介绍如何通过自定义钩子实现两个 woocommerce 商品(包括变体)的常规价格自动同步,当任一商品价格手动修改时,另一商品价格实时更新,确保价格严格一致。
在 WooCommerce 中,默认不支持跨商品的价格联动,但借助 WordPress 的动作钩子(如 updated_post_meta)与 WooCommerce 的产品 API,我们可以精准捕获价格变更事件并触发同步逻辑。以下方案不仅适用于普通商品,还可扩展支持变体——关键在于监听和更新正确的元字段(_regular_price 和 _sale_price),并确保事务安全与循环更新防护。
✅ 核心实现原理
我们监听 updated_post_meta 钩子,该钩子在任意商品元数据(包括价格)被保存后触发。通过判断 $post_id 和 $meta_key,仅对目标商品(A 和 B)的 _regular_price 变更作出响应,并调用 WC_Product::set_regular_price() + save() 实现反向同步。
? 完整可部署代码(支持基础商品)
将以下代码添加至当前主题的 functions.php 文件或专用插件中:
add_action( 'updated_post_meta', 'bind_product_prices', 10, 4 );
function bind_product_prices( $meta_id, $post_id, $meta_key, $meta_value ) {
// ⚙️ 配置需绑定的商品 ID(请替换为你的实际商品 ID)
$product_a_id = 21;
$product_b_id = 33;
// 仅处理目标商品且仅限价格元字段
if ( ! in_array( $post_id, [ $product_a_id, $product_b_id ] ) || $meta_key !== '_regular_price' ) {
return;
}
$new_price = floatval( $meta_value );
// 防止重复同步:若目标商品当前价格已匹配,跳过保存
if ( $post_id === $product_a_id ) {
$product_b = wc_get_product( $product_b_id );
if ( ! $product_b || ! $product_b->is_type( 'variation' ) && $product_b->get_regular_price() == $new_price ) {
return;
}
$product_b->set_regular_price( $new_price );
$product_b->save();
} elseif ( $post_id === $product_b_id ) {
$product_a = wc_get_product( $product_a_id );
if ( ! $product_a || ! $product_a->is_type( 'variation' ) && $product_a->get_regular_price() == $new_price ) {
return;
}
$product_a->set_regular_price( $new_price );
$product_a->save();
}
}
? 扩展支持变体(Variations)
上述代码默认适用于简单商品。若需同步变体价格,需额外监听变体的 _regular_price 元数据变更(变体是独立的 product_variation 类型文章),并使用 wc_get_product() 正确加载变体对象:
// 在原函数中补充对变体的支持(示例片段):
if ( get_post_type( $post_id ) === 'product_variation' ) {
$variation = wc_get_product( $post_id );
if ( ! $variation ) return;
// 假设你希望将变体 A 的价格同步给变体 B(需提前配置变体 ID 映射)
$target_variation_id = 123; // 替换为对应变体 ID
$target_variation = wc_get_product( $target_variation_id );
if ( $target_variation && $target_variation->get_regular_price() != $new_price ) {
$target_variation->set_regular_price( $new_price );
$target_variation->save();
}
}
? 提示:变体间价格绑定需明确映射关系(如“产品A的蓝色尺寸S变体 ↔ 产品B的黑色尺寸S变体”),建议通过自定义字段或数据库表维护映射,而非硬编码。
⚠️ 注意事项与最佳实践
- 避免无限循环:本方案通过 === 严格比较价格值+提前返回,防止 A→B→A 的递归触发;切勿在同步逻辑中再次调用 update_post_meta()。
- 权限与性能:该操作发生在后台编辑时,不影响前台访问速度;但若绑定商品量大,建议增加缓存或异步队列(如使用 wp_schedule_single_event)。
- 销售价同步:如需同时同步 _sale_price,可复制逻辑并替换 $meta_key 判断条件,但注意 set_sale_price() 与促销逻辑兼容性。
- 测试先行:务必在开发环境启用 WP_DEBUG 并测试手动修改价格、批量编辑、REST API 更新等场景。
通过此方案,你无需依赖第三方动态定价插件,即可实现轻量、可控、可维护的价格联动机制——真正让 WooCommerce 按需而变。










