Solution:
For WooCommerce, You don’t need to use any plugin for that
WooCommerce has already the dedicated WC_Geolocation
class that will do it better.
The code using WooCommerce WC_Geolocation
class instead:
// Utility function to get geolocated user country based on WooCommerce WC_Geolocation Class
function get_geolocated_user_country(){
// Get an instance of the WC_Geolocation object class
$geolocation_instance = new WC_Geolocation();
// Get user IP
$user_ip_address = $geolocation_instance->get_ip_address();
// Get geolocated user IP country code.
$user_geolocation = $geolocation_instance->geolocate_ip( $user_ip_address );
return $user_geolocation['country'];
}
// Disable purchasing of products if the country is not United States
add_filter('woocommerce_is_purchasable', 'purchasable_country_based', 10, 2);
function purchasable_country_based( $is_purchasable, $product ) {
// Enable for "US" only geolocated users country
if( get_geolocated_user_country() ==='US' )
return true;
else
return false;
}
// Filter out prices based on country
add_filter( 'woocommerce_variable_sale_price_html', 'display_prices_country_based', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'display_prices_country_based', 10, 2 );
add_filter( 'woocommerce_get_price_html', 'display_prices_country_based', 10, 2 );
function display_prices_country_based( $price, $product ) {
// Enable for "US" only geolocated users country
if( get_geolocated_user_country() === 'US' )
return $price;
else
return '';
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Now you might face some problems when US customers want to buy from another country, if they are travelling for example…
Woocommerce Geo IP related answer: