
本文介绍一种基于商品重量与全局单价字段自动计算并批量更新 woocommerce 商品售价的实用方案,适用于按克/千克计价的标准化商品(如贵金属、香料、茶叶等),确保价格随基础单价实时联动。
本文介绍一种基于商品重量与全局单价字段自动计算并批量更新 woocommerce 商品售价的实用方案,适用于按克/千克计价的标准化商品(如贵金属、香料、茶叶等),确保价格随基础单价实时联动。
在 WooCommerce 中实现“按重量动态定价”(如每克/每千克统一单价),关键在于解耦价格逻辑与商品数据:将基础单价(如 ¥2000/克)存入自定义字段,再根据每个商品的实际重量(_weight)实时计算最终售价,并批量写入 _regular_price 和 _sale_price 元数据。
以下是一个经过优化、安全可用的完整实现方案:
✅ 推荐实现方式(支持简单产品 & 变体产品)
// 将此代码添加到主题 functions.php 或专用插件中
add_action('admin_init', 'sync_product_prices_from_weight_unit_price');
function sync_product_prices_from_weight_unit_price() {
// 仅在手动触发时执行(避免每次 admin_init 都运行)
if (!isset($_GET['sync_wc_prices']) || !current_user_can('manage_woocommerce')) {
return;
}
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'post_status' => 'publish',
'fields' => 'ids'
);
$product_ids = get_posts($args);
foreach ($product_ids as $product_id) {
$product = wc_get_product($product_id);
if (!$product) continue;
// 获取单位价格(建议使用统一 meta key,如 '_unit_price_per_gram')
$unit_price = (float) get_post_meta($product_id, '_unit_price_per_gram', true);
if (!$unit_price || $unit_price <= 0) continue;
// 获取商品重量(单位:克 —— 注意:WooCommerce 默认 weight 单位为 kg,需转换!)
$weight_kg = $product->get_weight();
$weight_g = $weight_kg ? $weight_kg * 1000 : 0; // 转为克
// 计算最终价格(四舍五入保留2位小数)
$calculated_price = round($weight_g * $unit_price, 2);
// 同步 regular_price 和 sale_price(可选)
update_post_meta($product_id, '_regular_price', $calculated_price);
update_post_meta($product_id, '_price', $calculated_price); // 确保前台显示一致
// 若需同步促销价,可设为 same 或留空:update_post_meta($product_id, '_sale_price', $calculated_price);
}
// 完成后跳转并提示
wp_redirect(add_query_arg(array('prices_synced' => 'true'), wp_get_referer()));
exit;
}
// 添加后台一键同步按钮(位于 WooCommerce > 仪表盘)
add_action('admin_menu', 'add_price_sync_admin_page');
function add_price_sync_admin_page() {
add_management_page(
'同步商品价格',
'同步价格',
'manage_woocommerce',
'sync-wc-prices',
'render_sync_page'
);
}
function render_sync_page() {
if (isset($_GET['prices_synced']) && $_GET['prices_synced'] === 'true') {
echo '<div class="notice notice-success"><p>✅ 所有已发布商品价格已根据单位价格和重量重新计算并更新!</p></div>';
}
?>
<div class="wrap">
<h1>批量同步商品价格</h1>
<p><strong>说明:</strong>本工具将读取每个商品的「重量」与自定义字段 <code>_unit_price_per_gram</code>,自动计算 <code>重量(g) × 单价</code> 并更新售价。</p>
<a href="<?php echo wp_nonce_url(admin_url('admin.php?page=sync-wc-prices&sync_wc_prices=true'), 'sync_prices'); ?>"
class="button button-primary"
onclick="return confirm('⚠️ 此操作将覆盖所有商品当前价格,确定要执行吗?');">
? 立即同步全部商品价格
</a>
</div>
<?php
}
// 【重要】设置单位价格字段(推荐使用 ACF 或原生 meta box)
// 示例:在商品编辑页添加「每克单价」输入框
add_action('woocommerce_product_options_general_product_data', 'add_unit_price_field');
function add_unit_price_field() {
woocommerce_wp_text_input([
'id' => '_unit_price_per_gram',
'label' => __('每克单价(¥)', 'woocommerce'),
'description' => __('用于自动计算售价:重量(g) × 此值', 'woocommerce'),
'type' => 'number',
'custom_attributes' => ['step' => '0.01', 'min' => '0']
]);
}
add_action('woocommerce_process_product_meta', 'save_unit_price_field');
function save_unit_price_field($post_id) {
$value = isset($_POST['_unit_price_per_gram']) ? floatval($_POST['_unit_price_per_gram']) : '';
update_post_meta($post_id, '_unit_price_per_gram', $value);
}⚠️ 关键注意事项
- 重量单位一致性:WooCommerce 默认 get_weight() 返回 千克(kg),务必乘以 1000 转换为克(g),否则价格将严重偏低(如 2g 当作 2kg 计算 → 差1000倍)。
- 字段命名规范:避免使用模糊字段名(如 'afc-field')。推荐统一使用语义化 key:_unit_price_per_gram。
- 变体产品处理:上述脚本默认同步父级简单产品价格。若需同步变体(如不同克重规格),需遍历 product_variation 并获取其独立重量($variation->get_weight()),逻辑更复杂,建议单独扩展。
- 性能与安全:批量操作前务必备份数据库;生产环境建议增加 wp_nonce 验证及执行限制(如分批处理 + AJAX 分页)。
- 缓存兼容性:更新价格后,清除对象缓存(如 Redis)及页面缓存(如 WP Rocket),确保前台实时生效。
✅ 最佳实践:将该机制作为「价格基线控制」手段,配合定期手动触发同步(而非实时钩子),兼顾稳定性与可控性。后续还可扩展为「按时间段生效」或「多币种单价」等高级场景。
通过本方案,您只需修改一次 _unit_price_per_gram 字段,即可全局联动所有商品售价——真正实现轻量、可靠、可维护的价格管理体系。

















