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

WooCommerce实现产品新增时自动为Regular Price追加固定金额的技术求助

WooCommerce实现产品新增时自动为Regular Price追加固定金额的技术求助

我懂你的需求啦——你想要在产品成功添加到数据库时,自动给填写的「Regular Price」加上一个固定金额(比如例子里的5美元),让最终显示给客户的价格是加价后的数值。你找到的那段代码其实是用来当用户没填Regular Price时设置默认值为5美元,和你要的“在已有价格基础上追加金额”逻辑完全不符,所以才没起作用😅

给你修正后的代码,完全贴合你的需求:

function add_fixed_amount_to_regular_price( $post_id, $post ) {
    // 确保当前处理的是产品,且是已发布的新增产品(若要编辑产品时也生效,可去掉 'publish' !== $post->post_status 这部分)
    if ( 'product' !== $post->post_type || 'publish' !== $post->post_status || get_post_meta( $post_id, '_regular_price', true ) === '' ) {
        return;
    }

    // 这里设置你要追加的固定金额,改成你需要的数值即可
    $fixed_add_amount = 5;

    // 获取用户填写的原始常规价格,转成浮点型避免计算错误
    $original_price = floatval( get_post_meta( $post_id, '_regular_price', true ) );

    // 计算加价后的新价格
    $new_price = $original_price + $fixed_add_amount;

    // 更新产品的常规价格为加价后的值
    update_post_meta( $post_id, '_regular_price', $new_price );
    
    // 额外同步更新销售价(如果没设置销售价的话),保证前端显示的价格一致
    if ( get_post_meta( $post_id, '_sale_price', true ) === '' ) {
        update_post_meta( $post_id, '_sale_price', $new_price );
    }
}
add_action( 'woocommerce_process_product_meta', 'add_fixed_amount_to_regular_price', 10, 2 );

代码关键点说明:

  • 开头的判断是为了确保我们只处理产品类型的新增操作,避免误修改其他内容;如果希望编辑产品时改原价也自动加价,删掉'publish' !== $post->post_status这部分就行
  • $fixed_add_amount 是你要追加的固定金额,直接改成你需要的数字(比如10、15都可以)
  • 转成浮点型是为了避免字符串拼接式的错误计算(比如"25"+5变成"255"而不是30)
  • 同步更新销售价是因为WooCommerce前端有时候会优先读取销售价,没设置的话就显示常规价,同步后能确保客户看到的一定是加价后的价格

注意事项:

  • 把这段代码添加到你当前主题的functions.php文件末尾,或者用专门的自定义代码插件(比如Code Snippets)来添加,绝对不要直接修改WooCommerce的核心文件,不然更新插件后代码会丢失
  • 测试的时候新增一个产品,填25美元的Regular Price,提交后去产品后台看价格是不是变成30美元,再去前端确认显示是否正确

备注:内容来源于stack exchange,提问作者Geofrey Martin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.20 12:58:10