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

WooCommerce刷新片段时获取账单国家总是显示旧值的问题

问题根源

你触发片段刷新时,新选中的账单国家还没同步到后台的WC客户会话里,所以PHP端拿到的始终是旧值。

解决方案

1. 修改前端JS代码

在触发片段刷新时,把当前选中的国家值作为参数传递给后台:

jQuery(document).ready(function(){
    // 账单国家变更时,携带选中值刷新WC片段
    jQuery(document.body).on('change', 'select[name=billing_country]', function(){
        const selectedCountry = jQuery(this).val();
        // 触发片段刷新并传递选中的国家参数
        jQuery(document.body).trigger('wc_fragment_refresh', {
            billing_country: selectedCountry
        });
    });
});

2. 修改后端PHP函数

优先读取前端传递的国家参数,同时可选择将新值同步到客户会话(确保后续请求也能拿到最新值):

function wc_refresh_mini_cart_billing_country($fragments){
    ob_start();

    // 优先使用前端传递的新国家值,否则用客户对象中的旧值
    $billing_country = isset($_POST['billing_country']) ? sanitize_text_field($_POST['billing_country']) : WC()->customer->get_billing_country();

    // 可选:将新国家值同步到客户会话,保证后续请求一致性
    if(isset($_POST['billing_country'])){
        WC()->customer->set_billing_country($billing_country);
        WC()->customer->save();
    }

    // 输出国家代码
    echo $billing_country;

    // 更新片段内容
    $fragments['#your-billing-country'] = ob_get_clean();
    
    return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'wc_refresh_mini_cart_billing_country');

补充说明

  • WooCommerce的wc_fragment_refresh事件会自动将你传入的参数携带到AJAX请求中,后台可通过$_POST获取。
  • 使用sanitize_text_field是为了过滤恶意输入,保证安全性。
  • 同步客户对象的步骤为可选操作,如果仅需当前片段刷新显示正确值,可省略该部分。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 21:50:39