Home » WooCommerce: Detecting Current User Country (Geolocation)

WooCommerce: Detecting Current User Country (Geolocation)

by Tutor Aspire

In the redesign of Business Bloomer homepage, launched recently, I wanted to add some “personalization” to the main headline. In detail, I wanted to make use of PHP and WooCommerce inbuilt MaxMind Geolocation (when enabled from the General Settings Tab of course) to print a custom greeting on the screen.

The detection of 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. And as usual, this “detection” is done with one line of code!

The new Business Bloomer homepage with a “personalized” greeting based on Geolocated User Country

PHP Snippet: Get Current User Country (Geolocation) – WooCommerce

 

/**
 * @snippet       Get Current User Country (Geolocation) - WooCommerce
 * @how-to        Get tutoraspire.com FREE
 * @sourcecode    https://tutoraspire.com/?p=72811
 * @author        Tutor Aspire
 * @compatible    Woo 3.5.3
 * @donate $9     https://www.tutoraspire.com
 */

function tutoraspire_use_geolocated_user_country(){

// Geolocation must be enabled @ Woo Settings

$location = WC_Geolocation::geolocate_ip();
$country = $location['country'];

// Lets use the country to e.g. echo greetings

switch ($country) {
    case "IE":
        $hello = "Howya!";
        break;
    case "IN":
        $hello = "Namaste!";
        break;
    default:
        $hello = "Hello!";
}

echo $hello;
}

add_action( '_______', 'tutoraspire_use_geolocated_user_country' );

You may also like