Because it does not work?
I want it to also have the client’s IP to geolocate it help me
I already tried many times but I can’t get it to work.
function obtener_pais_por_ip() {
// Reemplaza 'TU_CLAVE_DE_API' con tu clave de API de ipstack
$api_key = 'TU_CLAVE_DE_API';
$user_ip = $_SERVER['REMOTE_ADDR'];
// Realizar la solicitud a ipstack
$response = wp_remote_get("http://api.ipstack.com/$user_ip?access_key=$api_key");
if (is_wp_error($response)) {
return false;
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body);
return $data->country_code;
}
function aplicar_descuento_por_pais($price, $product) {
$user_country = obtener_pais_por_ip();
// Define los países elegibles para el descuento y el porcentaje del descuento para cada país
$countries_discount = array(
'ES' => 10, // 10% de descuento para España (código ISO 'ES')
'US' => 15, // 15% de descuento para Estados Unidos (código ISO 'US')
// Agrega más países y sus respectivos porcentajes de descuento según tus necesidades
);
if (isset($countries_discount[$user_country])) {
// Aplicar el descuento si el país del usuario está en la lista de países elegibles
$discounted_price = $price * (1 - ($countries_discount[$user_country] / 100));
return $discounted_price;
}
// Si el país del usuario no está en la lista de países elegibles, retornar el precio sin descuento
return $price;
}
add_filter('woocommerce_product_get_price', 'aplicar_descuento_por_pais', 10, 2);
I want to make them have discounts depending on the country
2
Answers
It didn't work for me, make the price change even if it's not the country, help
Let’s use the functional WooCommerce geolocation instead (integrated with Maxmind GeoLite2 free for countries). The settings are in Woocommerce > Settings > Integration (and require opening a free account in Maxmind).
Also, if you like, in General woocommerce settings, you can set the "Default customer location" to "Geolocation".
The code:
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Related: WooCommerce and MaxMind Geolocation Integration