【问题标题】:How to switch currency programatically using WooCommerce Multilingual & Multicurrency plugin如何使用 WooCommerce 多语言和多货币插件以编程方式切换货币
【发布时间】:2023-02-02 14:34:15
【问题描述】:
我需要能够通过添加特定链接在 WooCommerce 网站上切换货币。在客户的网站上安装了 OnTheGoSystems 的 WooCommerce 多语言和多货币。
我现在有这样的事情:
add_filter( 'wcml_client_currency', 'abc_client_currency' );
function abc_client_currency( $currency ) {
if( !empty( $_GET['country'] ) ) {
switch ( $_GET['country']) {
case 'US':
$new_currency = 'USD';
break;
case 'PL':
$new_currency = 'PLN';
break;
default:
$new_currency = 'EUR';
break;
}
$settings = get_option( '_wcml_settings' );
$currencies = $settings['currency_options'];
$currency_codes = array_keys( $currencies );
if( in_array( $new_currency, $currency_codes ) ) {
return $new_currency;
}
}
return $currency;
}
它适用于第一个页面加载(只要 url 中有 ?contry=XY)。我知道我可以将货币保存到 cookie/session 中并继续使用这种方法,但这并不正确。我想正确地转换货币。
【问题讨论】:
标签:
wordpress
woocommerce
currency
【解决方案1】:
假设您有某种用于在货币之间进行选择的下拉列表:
<ul id="curr_switcher">
<li class="country" data-country="US">USD</li>
<li class="country" data-country="PL">PLN</li>
<li class="country" data-country="FR">EUR</li>
</ul>
我会使用一些简单的 jQuery 连接到 wp_footer 操作(不是 wp_head,因为 jQuery 可能还没有加载)以在用户单击时使用正确的变量重定向到同一页面/位置 - 只需将它连接到 wp_footer 操作以在所有前端加载-结束页面:
<?php
add_action('wp_footer', function () { ?>
<script>
jQuery(document).ready(function($) {
// .country on click
$('.country').click(function(e) {
// prevent default behaviour
e.preventDefault();
// retrieve country code
var country = $(this).data('country');
// retrieve current location pathname
var current_loc_path = window.location.pathname;
// append currency argument to pathname
var new_loc_path = current_loc_path + '/?country=' + country;
// use location replace to redirect page with correctly appended currency as argument
window.location.replace(new_loc_path);
});
});
</script>
<?php }); ?>
因此,简而言之,您正在检索当前浏览器窗口的位置路径,在单击时将所选国家/地区附加到该路径,然后基本上重新加载页面(从技术上讲是一个完整的重定向,但我们不要在这里分头)。
请注意,这可能不是最“技术上正确”的方法 - 可能还有其他更复杂的方法来实现同样的事情 - 但我的倾向总是寻找最简单的解决方案,只要它有效并且你的代码已妥善评论,供日后参考!
另请注意:这可能不会超过当前页面 - 将国家参数附加到您希望为其加载正确货币的所有链接可能是个好主意。
希望以上内容能让您朝着正确的方向开始。