Search code examples
switch-statementwoocommercecurrency

Change currency position according to currency in wordpress


Googled and searched but I couldn't find what I was looking for.

I am building a woocommerce website which has 2 currencies: KRW and USD.

I have two buttons which switch between these currencies.

When KRW is selected, price display 10,000W and when USD is selected, it displays 100$.

What I want is to display $100 when USD is selected.

I tried in my 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;
}

also tried:

    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');

Both didn't work. :(

Can somebody help please. Thank you.


Solution

  • This is just a guess since I don't know what plugin you are using or how it works. I am going to assume that it adds a $_GET variable named currency to the end of your URL. www.example.com&currency=KRW But idea is that you set a value for the woocommerce_currency_pos option based on some data provided by the currency plugin.

    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';
        } 
    }
    

    Alternatively, I could assume that "right" is the default currency position. And that you only need to filter the option in the instance where the site is displayed in USD-mode. In which case you would only need the following

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