Menu Close

WooCommerce: Detecting Current User Country (Geolocation)

default

You may need to add some “personalization” to your WooCommerce website homepage. For example, you could print a custom greeting based on the user’s IP address.

For that, you can use PHP and WooCommerce inbuilt MaxMind Geolocation integration (when enabled from the General Settings Tab, of course).

Detecting the current user country could be very useful for other tasks, such as disabling payment gateways and shipping methods, printing country-specific content and so on. Enjoy!

An old version of the Business Bloomer website homepage featured a “personalized” greeting based on Geolocated User Country. I’ve since removed it, but the code is still valid!

PHP Snippet: Get Current User Country (Geolocation) To Display Conditional Content – WooCommerce

/**
 * @snippet       Get Current User Country - WooCommerce
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 7
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

add_action( '_______', 'bbloomer_use_geolocated_user_country' );

function bbloomer_use_geolocated_user_country(){
   // Geolocation must be enabled @ Woo Settings
   $location = WC_Geolocation::geolocate_ip();
   $country = $location['country'];
   // Lets use the country to echo greetings
   switch ( $country ) {
      case "IE":
         $hello = "Howya!";
         break;
      case "IN":
         $hello = "Namaste!";
         break;
      default:
         $hello = "Hello!";
   }
   echo $hello;
}
View Source
Posted in WooCommerce Tips