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

如何修改WooCommerce短代码实现免息分期金额计算并显示货币符号

修改WooCommerce短代码实现4期免息付款提示

以下是满足需求的完整修改代码,同时解决了货币符号显示和分期计算的问题:

add_shortcode( 'installment_prompt', 'display_installment_prompt' );
function display_installment_prompt( $atts ){
    // 设置默认参数:商品ID默认当前页面商品,分期期数默认4期
    $atts = shortcode_atts( array(
        'id' => get_the_id(),
        'installments' => 4,
    ), $atts, 'installment_prompt' );

    global $product;
    // 确保获取到有效的WooCommerce商品对象
    if ( ! is_a( $product, 'WC_Product') ) {
        $product = wc_get_product($atts['id']);
    }

    // 检查商品是否存在且价格有效
    if ( ! $product || ! $product->get_price() ) {
        return ''; // 商品无效时返回空内容,避免前端显示错误
    }

    $product_price = (float)$product->get_price();
    $installment_count = (int)$atts['installments'];
    // 计算每期金额,强制保留两位小数符合货币规范
    $per_installment = number_format( $product_price / $installment_count, 2 );

    // 使用WooCommerce内置函数格式化金额,自动适配后台设置的货币符号、格式
    $formatted_amount = wc_price( $per_installment );

    // 返回最终的提示文本
    return sprintf( '分%d期免息付款,每期%s', $installment_count, $formatted_amount );
}

关键修改说明:

  • 重命名短代码为installment_prompt,功能指向更清晰(如需保留原名称product_price,直接替换短代码名称即可)
  • 新增installments参数,默认4期,后续可灵活调整分期数
  • 用wc_price()替代直接返回纯数字,自动匹配你在WooCommerce后台设置的货币符号、千位分隔符等规则
  • 增加商品有效性检查,避免无效商品或无价格商品导致报错
  • 用number_format()确保每期金额保留两位小数,符合货币显示标准

使用方式:

  • 在商品页面直接插入短代码:[installment_prompt]
  • 指定商品ID或调整分期数:[installment_prompt id="123" installments="6"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 09:09:18