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

如何在WooCommerce结账页面添加可选额外费用(礼品包装)

在WooCommerce购物车和结账页面同时显示礼品包装选项

你当前的代码仅能在购物车页面展示ID为971的礼品包装商品添加选项,要让该选项同步出现在结账页面,只需给功能函数绑定结账页面对应的钩子即可,具体修改如下:

核心调整点

  • 原代码仅绑定了购物车页面钩子 woocommerce_cart_totals_after_shipping,需新增结账页面钩子 woocommerce_review_order_after_shipping
  • 初始化$found变量,避免PHP未定义变量警告
  • 改用WC()->cart替代全局$woocommerce对象(WooCommerce官方推荐写法)
  • 新增循环终止语句,提升代码执行效率

修改后的完整代码

<?php
/* ADD custom theme functions here  */
add_filter( 'woocommerce_price_trim_zeros', 'wc_hide_trailing_zeros', 10, 1 );
function wc_hide_trailing_zeros( $trim ) {
    return true;
}

// 同时绑定购物车、结账页面的钩子
add_action('woocommerce_cart_totals_after_shipping', 'wc_display_gift_wrapper_option');
add_action('woocommerce_review_order_after_shipping', 'wc_display_gift_wrapper_option');

function wc_display_gift_wrapper_option() {
    $product_id = 971;
    $found = false; // 初始化变量

    // 遍历购物车检查是否已添加礼品包装
    foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
        $_product = $values['data'];
        if ( $_product->get_id() == $product_id ) {
            $found = true;
            break; // 找到目标商品后立即终止循环
        }
    }

    // 根据状态渲染对应内容
    if ( ! $found ):
?>
    <tr class="shipping">
        <th><?php _e( 'Gift wrapper', 'woocommerce' ); ?></th>
        <td><a href="<?php echo do_shortcode('[add_to_cart_url id="971"]'); ?>"><?php _e( 'Add ($3)' ); ?> </a></td>
    </tr>
<?php else: ?>
    <tr class="shipping">
        <th><?php _e( 'Gift wrapper', 'woocommerce' ); ?></th>
        <td>$3</td>
    </tr>
<?php endif;
}

补充说明

  • woocommerce_review_order_after_shipping是结账页面订单摘要区域、运费模块之后的钩子,和购物车页面的钩子位置逻辑一致
  • 复用同一个函数绑定两个钩子,避免代码冗余
  • 使用get_id()替代旧版id属性,兼容WooCommerce 3.0及以上版本

内容的提问来源于stack exchange,提问作者André Rettedal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 01:55:37