WordPress如何通过AJAX更新购物车wc_price 无需刷新页面即可生效
实现无刷新更新免邮提示金额步骤
1. 修改原有模板代码
先把现有代码里的免邮提示部分改造,给动态金额增加独立标识,同时将免邮阈值输出到前端供JS调用:
<div class="cpops-drawer-header"> <?php do_action( 'cartpops_drawer_header' ); ?> </div> <div class="cpops-drawer-cart"> <?php do_action( 'cartpops_drawer_cart_contents' ); ?> </div> <?php $min_amount = 300; // 免邮阈值 $current = WC()->cart->subtotal_ex_tax; ?> <!-- 把阈值输出到前端JS变量 --> <script> window.free_shipping_min = <?php echo $min_amount; ?>; </script> <span class="min_amount_class" id="min_amount_class" style="color:#ac192b;font-weight:bold;font-size:18px;<?php if($current >= $min_amount) echo 'display:none;'; ?>"> 税前再消费 <span id="shipping_diff_amount"><?php echo wc_price( $min_amount - $current ); ?></span> 即可享受免邮! </span> <div class="cpops-drawer-footer"> <?php do_action( 'cartpops_drawer_coupon_form' ); ?> <?php do_action( 'cartpops_drawer_recommendations' ); ?> <?php do_action( 'cartpops_drawer_totals' ); ?> <?php do_action( 'cartpops_powered_by' ); ?> </div>
2. 新增后端AJAX处理接口
把以下代码添加到当前主题的functions.php文件中,用于处理AJAX请求返回最新的差额金额:
// 登录用户AJAX接口 add_action('wp_ajax_get_shipping_diff', 'get_shipping_diff_callback'); // 访客用户AJAX接口 add_action('wp_ajax_nopriv_get_shipping_diff', 'get_shipping_diff_callback'); function get_shipping_diff_callback() { $min_amount = 300; // 和前端的免邮阈值保持一致 $current = WC()->cart->subtotal_ex_tax; $res = [ 'need_more' => $current < $min_amount, 'diff_html' => $current < $min_amount ? wc_price($min_amount - $current) : '' ]; wp_send_json_success($res); wp_die(); }
3. 新增前端JS更新逻辑
把以下JS代码添加到主题的自定义JS文件,或者直接放到页脚模板中,触发时机可以根据实际交互调整:
// 定义更新免邮提示的方法 function updateShippingNotice() { jQuery.ajax({ url: '/wp-admin/admin-ajax.php', type: 'POST', data: { action: 'get_shipping_diff' }, success: function(res) { if(res.success) { if(res.data.need_more) { jQuery('#min_amount_class').show(); jQuery('#shipping_diff_amount').html(res.data.diff_html); } else { jQuery('#min_amount_class').hide(); } } } }); } // 监听WooCommerce自带的购物车更新事件 jQuery(document).on('updated_cart_totals', updateShippingNotice); // 如果侧栏抽屉有自定义打开事件,也可以加上触发,假设抽屉打开事件是cartpops_drawer_open jQuery(document).on('cartpops_drawer_open', updateShippingNotice); // 加购、减购商品成功后也可以主动调用 updateShippingNotice() 方法触发更新
优化提示:如果站点有自定义AJAX路径配置,可以把JS中的AJAX地址替换为WooCommerce全局变量
wc_add_to_cart_params.ajax_url,兼容性更好。
内容的提问来源于stack exchange,提问作者kks
相关产品推荐
相关产品推荐

