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

WooPayments多币种插件AJAX加载商品时币种不切换问题求助

解决WooPayments Multi-Currency AJAX加载商品币种不更新问题
  • 传递选中币种到AJAX请求
    在触发AJAX加载的前端代码中,把当前选中的币种参数附加到请求数据里。可以从插件存储的Cookie或页面上的币种选择控件获取值,示例代码:

    jQuery.ajax({
        url: ajaxurl,
        type: 'POST',
        data: {
            action: 'your_custom_load_products',
            // 获取当前选中的币种
            selected_currency: Cookies.get('wcpay_selected_currency') || jQuery('.wcpay-multi-currency-selected').data('currency')
        },
        success: function(res) {
            jQuery('.product-listing').html(res);
        }
    });
    
  • 后端AJAX回调中切换币种上下文
    在处理商品加载的PHP回调函数里,接收前端传递的币种参数,强制设置当前会话的币种,确保商品查询时使用选中的币种计算价格:

    add_action('wp_ajax_your_custom_load_products', 'custom_load_products_callback');
    add_action('wp_ajax_nopriv_your_custom_load_products', 'custom_load_products_callback');
    
    function custom_load_products_callback() {
        // 验证币种合法性(替换为你的实际币种列表)
        $allowed_currencies = ['USD', 'EUR', 'JPY'];
        if (isset($_POST['selected_currency']) && in_array($_POST['selected_currency'], $allowed_currencies)) {
            $selected_currency = sanitize_text_field($_POST['selected_currency']);
            // 设置WooPayments会话币种
            WC()->session->set('wcpay_selected_currency', $selected_currency);
            // 同步WooCommerce币种上下文
            if (class_exists('WC_Payments_Multi_Currency')) {
                $multi_currency = WC_Payments_Multi_Currency::get_instance();
                $multi_currency->set_selected_currency($selected_currency);
            }
        }
    
        // 加载并输出商品模板
        ob_start();
        $products_query = new WP_Query([
            'post_type' => 'product',
            'posts_per_page' => 8
        ]);
        if ($products_query->have_posts()) {
            while ($products_query->have_posts()) {
                $products_query->the_post();
                wc_get_template_part('content', 'product');
            }
        }
        wp_reset_postdata();
        echo ob_get_clean();
        wp_die();
    }
    
  • 确保模板使用标准价格函数
    商品模板中必须使用WooCommerce的标准价格输出函数(如wc_get_price_to_display()、the_price()),不要直接调用数据库原始价格,这样才能自动应用币种转换逻辑。

  • 排除AJAX请求的缓存
    如果网站启用了缓存插件,要将AJAX商品加载的请求URL排除在缓存之外,或者在缓存键中加入币种参数,避免不同币种返回相同的缓存内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 15:17:07