WooCommerce结账页为费用添加折叠式免责声明的实现方法
实现WooCommerce结账费用项的可折叠免责声明
你可以通过WooCommerce专属钩子配合前端代码实现需求,无需修改原附加费核心逻辑,只需新增几个功能模块:
1. 保留并优化原附加费代码
原代码负责添加美国地区3美元附加费,修正拼写错误后可直接复用:
function wc_add_surcharge() { global $woocommerce; if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; $countries = array('US'); // 修正原变量名拼写错误:county → countries $fee = 3.00; if ( in_array( WC()->customer->get_shipping_country(), $countries ) ) : $woocommerce->cart->add_fee( '附加费名称', $fee, true, 'standard' ); endif; } add_action( 'woocommerce_cart_calculate_fees', 'wc_add_surcharge' );
2. 添加钩子插入可折叠免责声明
使用woocommerce_cart_totals_after_fee钩子,在附加费下方插入折叠面板HTML:
function wc_add_fee_disclaimer() { // 仅针对美国地区附加费显示免责声明 if ( in_array( WC()->customer->get_shipping_country(), array('US') ) ) : ?> <div class="fee-disclaimer-container"> <button class="disclaimer-toggle">查看免责声明</button> <div class="disclaimer-content" style="display:none;"> <p>这里填写你的免责声明内容,比如:此附加费用于覆盖美国境内物流处理成本,费用不含税费,最终金额以结账页面显示为准。</p> <p>可添加多行文本或其他HTML元素</p> </div> </div> <?php endif; } add_action( 'woocommerce_cart_totals_after_fee', 'wc_add_fee_disclaimer' );
3. 添加CSS优化显示效果
将以下代码添加到主题自定义CSS区域或子主题style.css文件:
.fee-disclaimer-container { margin-top: 8px; padding-left: 15px; } .disclaimer-toggle { background: none; border: none; color: #0073aa; cursor: pointer; font-size: 14px; padding: 0; text-decoration: underline; } .disclaimer-toggle:hover { color: #006799; } .disclaimer-content { margin-top: 8px; font-size: 13px; color: #555; line-height: 1.5; }
4. 添加JS实现折叠切换功能
将以下代码添加到主题自定义JS区域或通过wp_enqueue_script加载:
document.addEventListener('DOMContentLoaded', function() { const toggleButtons = document.querySelectorAll('.disclaimer-toggle'); toggleButtons.forEach(button => { button.addEventListener('click', function() { const content = this.nextElementSibling; if (content.style.display === 'none') { content.style.display = 'block'; this.textContent = '收起免责声明'; } else { content.style.display = 'none'; this.textContent = '查看免责声明'; } }); }); });
说明
- 钩子
woocommerce_cart_totals_after_fee会在每个费用项后插入内容,刚好对应附加费下方位置 - 前端代码实现了点击按钮切换显示/隐藏的效果,与你提供的示例逻辑一致
- 所有代码可直接添加到主题
functions.php(推荐用子主题,避免主题更新丢失修改)
内容的提问来源于stack exchange,提问作者Coleman Geiger
相关产品推荐
相关产品推荐

