The code in this article is considered a customisation. As such, it's outside the scope of our support service. Should you need assistance implementing the code, please feel free to contact us to request a consultation.


Setting the currency for current session and user's profile

The Currency Switcher will check for a selected currency during the woocommerce_init event. To force the selected currency to a specific one, set the value of $POST ["aelia_cs_currency"] in a hook attached to woocommerce_init event (the user is already authenticated when such event is fired). The hook must have a priority of 0 (zero), as the Currency Switcher will run its own with a priority of 1.


Examples

To use the code in the examples, simply place it in your theme's functions.php. See How to Safely Add Custom Code to WordPress Sites for more information on how to do that.


Example 1 - Forcing a specific currency in all cases

This example shows how to force the currency to a specific value on page load. The currency is also stored in user's cookies and in user's profile. The set currency will be used for any subsequent page load. Selecting another currency manually will not have any effect, this code will force it back to USD.

This code is useful if you would like to use the Currency Switcher features to enter product prices in multiple currencies in the backend, but you would like to sell them in a single currency.  

function set_currency_programmatically() {
  // Only change the currency on the frontend
  if(!is_admin() || defined('DOING_AJAX')) {
    // Always force selected currency to US Dollars
    // This will ensure that all customers will always see prices
    // and place orders in USD
    $_POST['aelia_cs_currency'] = 'USD';
  }
}
add_action('woocommerce_init', 'set_currency_programmatically', 0);

  

Example 2 - Selecting the currency depending on the active language

This example is designed to work with WPML, you might have to adapt it to other multi-language plugins.        

function set_currency_by_language() {
  // Only change the currency on the frontend
  if(!is_admin() || defined('DOING_AJAX')) {
    // Map each language to a currency
    $language_currency_map = array(
      // German = EUR
      'de' => 'EUR',
      // Sweden = SEK
      'sv' => 'SEK',
      // Norway = NOK
      'no' => 'NOK',
    );
    
    if(defined('ICL_LANGUAGE_CODE') && isset($language_currency_map[ICL_LANGUAGE_CODE])) {
      $_POST['aelia_cs_currency'] = $language_currency_map[ICL_LANGUAGE_CODE];
    }
    else {
      // Default: USD
      $_POST['aelia_cs_currency'] = 'USD';
    }  
  }
}
add_action('woocommerce_init', 'set_currency_by_language', 0);

        

Example 3 - Setting the currency temporarily

If you want to set the currency only temporarily, for a specific page load, you can write a filter for hook wc_aelia_cs_selected_currency.  

function set_currency_programmatically($selected_currency) {
  // Force selected currency to US Dollars
  $selected_currency = 'USD';

  return $selected_currency;
}
add_filter('wc_aelia_cs_selected_currency', 'set_currency_programmatically', 0);

   

The above filter will set the currency only for current page load. User's cookies and profile will be unaffected, thus the currency stored in them will be used on next page load (unless you change it again, via code). 


Example 4 - Manually setting the currency against user's session and profile

If you wish to store the currency in user's cookie and profile, you can use the following code.   

// Let's set the currency to USD
$selected_currency = 'USD';
// Store currency in cookies
wc_setcookie('aelia_cs_selected_currency', $selected_currency);

// Store currency in user's profile (user meta)
$user_id = get_current_user_id();
update_user_meta($user_id, 'aelia_cs_selected_currency', $selected_currency);

  

Example 5 - Setting a specific currency for search engine crawlers

Out of the box, search engine crawlers are treated like any other visitor. If you need to make sure that crawlers receive a specific currency, the code below shows how you can do that.

function aelia_visitor_is_bot() {
  $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
  $bot_types = 'bot|crawl|slurp|spider';

  return !empty($user_agent) ? preg_match("/$bot_types/", $user_agent) > 0 : false;
}

function set_currency_for_bots() {
  // Only change the currency for bots, and only on the frontend
  if(aelia_visitor_is_bot() && (!is_admin() || defined('DOING_AJAX'))) {
    // Always force selected currency to US Dollars. Bots will always see prices
    $_POST['aelia_cs_currency'] = 'USD';
  }
}
add_action('woocommerce_init', 'set_currency_for_bots', 0);


Example 6 - Forcing checkout in a specific currency

If you wish to allow customers to browse the site in a currency of their choice, but force them to complete the checkout in a specific currency, the following code shows an example of how you can do that.

/**
 * Adds parameters to the Ajax request used to refresh the minicart. The additional
 * parameters will be used to determine the context in which the request was made,
 * so that we can know if we should force the currency because we are on the
 * checkout page.
 *
 * @param array params An array of parameters.
 * @return array
 */
add_filter('wc_cart_fragments_params', function($params) {
  if(is_checkout()) {
    if(strpos($params['wc_ajax_url'], '?') > 0) {
      $params['wc_ajax_url'] .= '&';
    }
    else {
      $params['wc_ajax_url'] .= '?';
    }
    // Add a parameter to the Ajax request, to keep track that it was triggered
    // on the checkout page
    $params['wc_ajax_url'] .= 'aelia_context=checkout';
  }
  return $params;
});

/**
 * Determines if we are processing an Ajax request triggered on the checkout page.
 *
 * @return bool
 */
function aelia_is_checkout_ajax_request() {
  if(defined('DOING_AJAX')) {
    // The "update_order_review" request updates the totals on the checkout
    // page
    if($_REQUEST['wc-ajax'] === 'update_order_review') {
      return true;
    }

    // The "get_refreshed_fragments" updates the minicart. We only need to take
    // it into account if we are on the checkout page
    if(($_REQUEST['wc-ajax'] === 'get_refreshed_fragments') &&
       ($_REQUEST['aelia_context'] === 'checkout')) {
      return true;
    }
  }
  return false;
}

/**
 * Forces the checkout currency to USD.
 *
 * @param string selected_currency The currency selected originally.
 * @return string
 */
add_filter('wc_aelia_cs_selected_currency', function($selected_currency) {
  // If we are on the checkout page, or handling an Ajax request from that page,
  // force the currency to USD
  if(is_checkout() || aelia_is_checkout_ajax_request()) {
    $selected_currency = 'USD';
  }
  return $selected_currency;
}, 50);


Example 7 - Forcing the currency depending on user's role

If you wish to force the currency depending on which role was assigned to the active user, the following example will show you how to do that. Please note that, if a user has multiple roles, the code in the example might match more than one. In such case, the last matching role will determine the currency.

/**
 * Apply a different currency based on the user role.
 *
 * @param string selected_currency The currency selected by the Currency Switcher.
 * @return string A currency code.
 * @author Aelia <support@aelia.co>
 */
function aelia_set_currency_by_role($selected_currency) {
  if(is_user_logged_in()) {
    $current_user = wp_get_current_user();
    
    // Set the currency to EUR for EU Distributors
    if(in_array('eu_distributor', $current_user->roles)) {
      $selected_currency = 'EUR';
    }

    // Set the currency to USD for US Distributors
    if(in_array('us_distributor', $current_user->roles)) {
      $selected_currency = 'USD';
    }
  }
  return $selected_currency;
}
add_filter('wc_aelia_cs_selected_currency', 'aelia_set_currency_by_role', 10, 1);

Important notes

  • The Currency Switcher was designed to allow customers to pay in their currency of choice. Forcing the checkout in an arbitrary currency could impact on conversion, as customers might be presented with a different currency from the one they were looking at.
  • Forcing the checkout in a specific currency will set the prices to the ones you specified for that currency. Example:
    1- You set the price of Product A to 100 USD and 100 EUR.
    2- You use the custom code to force the checkout in USD.
    3- A customer browses the site in EUR and see the product price as "100 EUR".

    When the customer will reach the checkout, the currency will be force to USD and the product price will be 100 USD (i.e. the price you set for the product at step #1), not "100 EUR converted to USD".


You can purchase the Currency Switcher from our online shop.