businessdad icon

Aelia Currency Switcher - Force currency at checkout

businessdad | PRO | 03/18/17 10:42:11 AM UTC | 0 ⭐ | 1224 👁️ | Never ⏰ | []
PHP |

2.35 KB

|

None

|

0 👍

/

0 👎

/**
 * Extract from support article https://aelia.freshdesk.com/solution/articles/3000010676
 * 
 * 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.
 *
 * Need help customising the code for your need? Hire us on Codeable: http://bit.ly/codeable_aelia
 */
 
/**
 * 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() || is_checkout_ajax_request()) {
    $selected_currency = 'USD';
  }
  return $selected_currency;
}, 50);

Comments