Skip to content

Instantly share code, notes, and snippets.

@jdevalk
Last active January 26, 2024 07:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdevalk/bb3efd2932bb45bec885149017d278e0 to your computer and use it in GitHub Desktop.
Save jdevalk/bb3efd2932bb45bec885149017d278e0 to your computer and use it in GitHub Desktop.

EDD Multi-currency currency by country switcher

The worker.js Cloudflare worker below determines the currency and sets a cookie. The PHP code reads the cookie and sets the session currency in EDD.

<?php
/**
* Set EDD currency from cookie set by Cloudflare.
*/
add_action( 'init', function() {
if ( isset( $_COOKIE['ft_currency'] ) ) {
$currency = $_COOKIE['ft_currency'];
if ( in_array( $currency, [ 'EUR', 'USD' ], true ) ) {
$current_currency = EDD()->session->get( 'currency' );
if ( $current_currency !== $currency ) {
EDD()->session->set( 'currency', $currency );
}
}
}
} );
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
/**
* Handle the fetch event.
*
* @param {Request} request The incoming request.
* @return {Promise<Response>} The response.
*/
async function handleRequest(request) {
// Clone the request to ensure it's not modified.
const response = await fetch(request.clone());
// Check if the 'ft_currency' cookie is already set.
const cookie = getCookie(request, 'ft_currency');
if (cookie) {
return response;
}
// Set the currency based on the country of the visitor.
// Cloudflare provides the country in the request headers.
const country = request.headers.get('cf-ipcountry');
let currency = 'USD';
if (['AT', 'BE', 'BG', 'CY', 'CZ', 'DE', 'DK', 'EE', 'ES', 'FI', 'FR', 'GR', 'HR', 'HU', 'IE', 'IT', 'LT', 'LU', 'LV', 'MT', 'NL', 'PL', 'PT', 'RO', 'SE', 'SI', 'SK', 'GB'].includes(country)) {
currency = 'EUR';
}
// Set the 'ft_currency' cookie in the response.
const newResponse = new Response(response.body, response);
newResponse.headers.append('Set-Cookie', `ft_currency=${currency}; path=/; HttpOnly; Secure`);
return newResponse;
}
/**
* Get a cookie from the request.
*
* @param {Request} request The request object.
* @param {string} name The name of the cookie.
* @return {string|null} The cookie value or null if not found.
*/
function getCookie(request, name) {
let result = null;
const cookieString = request.headers.get('Cookie');
if (cookieString) {
const cookies = cookieString.split(';');
cookies.forEach(cookie => {
const parts = cookie.split('=');
if (parts[0].trim() === name) {
result = parts[1];
}
});
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment