根据wordpress中的货币更改货币位置

Change currency position according to currency in wordpress

用 Google 搜索了很多,但找不到我要找的东西。

我正在建立一个有 2 种货币的 woocommerce 网站:KRW 和 USD。

我有两个按钮可以在这些货币之间切换。

选择KRW时价格显示10,000W,选择USD时显示100$。

我想要的是选择美元时显示$100。

我在 functions.php 中尝试过:

add_filter('woocommerce_price_format','change_currency_pos');

function change_currency_pos( $currency_pos, $currency ) {
     switch( $currency ) {
          case 'USD': $currency_pos = '%1$s%2$s'; break;
          case 'KRW': $currency_pos = '%2$s%1$s'; break;
     }
     return $currency_pos;
}

也尝试过:

    function change_currency_pos() {
        $currency_pos = get_option('woocommerece_currency');

        switch($currency_pos) {
            case 'USD': $format = '%1$s%2$s'; break;
            case 'KRW': $format = '%2$s%1$s'; break;
        }
        return $currency_pos;
        }

   add_filter('woocommerce_price_format','change_currency_pos');

两者均无效。 :(

有人可以帮忙吗?谢谢。

这只是一个猜测,因为我不知道您使用的是什么插件,也不知道它是如何工作的。我假设它在 URL 的末尾添加了一个名为 currency$_GET 变量。 www.example.com&currency=KRW 但想法是根据货币插件提供的一些数据为 woocommerce_currency_pos 选项设置一个值。

add_filter( 'pre_option_woocommerce_currency_pos', 'change_currency_position' );
function change_currency_position(){
    if( ! isset( $_GET['currency'] ) {
        return false;
    }

    if ( 'USD' == $_GET['currency'] ){
        return 'left';
    } elseif ( 'KRW' == $_GET['currency'] ){
        return 'right';
    } 
}

或者,我可以假设 "right" 是默认货币头寸。并且您只需要在站点以美元模式显示的实例中过滤该选项。在这种情况下,您只需要以下内容

add_filter( 'pre_option_woocommerce_currency_pos', 'change_currency_position' );
function change_currency_position(){
    if( isset( $_GET['currency'] && 'USD' == $_GET['currency'] ){
        return 'left';
    } 
}

要使 woocommerce_price_format 正常工作,您需要像这样设置格式

add_filter('woocommerce_price_format', 'woo_custom_format_position', 999, 2);
     
    function woo_custom_format_position($format, $currency_pos)
    {
      /*'left':$format = '%1$s%2$s';
       'right':$format = '%2$s%1$s';
       'left_space':$format = '%1$s %2$s';
       'right_space':$format = '%2$s %1$s';
      */
        $format = '%1$s%2$s';//Change your position
        return $format;
        
    }

由于某些奇怪的原因,'position' 设置不适用于欧元货币。我必须将此添加到我的 functions.php 才能修复它:

add_filter('woocommerce_price_format', 'woo_custom_format_position', 999, 2);
function woo_custom_format_position($format, $currency_pos)
{
  /*'left':$format = '%1$s%2$s';
   'right':$format = '%2$s%1$s';
   'left_space':$format = '%1$s %2$s';
   'right_space':$format = '%2$s %1$s';
  */
    switch ($currency_pos) {
        case 'left':
            return '%1$s%2$s';
        case 'right':
            return '%2$s%1$s';
        case 'left_space':
            return '%1$s %2$s';
        case 'right_space':
            return '%2$s %1$s';
        };
}

现在它实际使用在设置中选择的位置。

希望对大家有所帮助!