Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get user geolocated country name in Woocommerce 3

I would like to add "We ship to {country name}" in WooCommerce header based on user geoip country name?

I would like to write html content in the header of my WooCommerce store, such as We ship to "Your Country name".

Any help will be really appreciated?

I have WooCommerce geolocation enabled already.

like image 251
Kristina Avatar asked Jul 10 '18 22:07

Kristina


People also ask

How do I set geolocation in WooCommerce?

Go to: WooCommerce > Settings > General. Head to the General options section. In the “Default customer address” dropdown, choose “Geolocate” or “Geolocate (with page caching support)”

What is geolocate on WooCommerce?

Geolocation WooCommerce is a WordPress plugin that allows you to geoTarget your products and services to specific countries or regions. It is a powerful tool for online businesses that want to Target a global audience, or those that want to restrict their products and services to certain countries or regions.


1 Answers

You can make a custom function based on WC_Geolocation Class this way:

function get_user_geo_country(){
    $geo      = new WC_Geolocation(); // Get WC_Geolocation instance object
    $user_ip  = $geo->get_ip_address(); // Get user IP
    $user_geo = $geo->geolocate_ip( $user_ip ); // Get geolocated user data.
    $country  = $user_geo['country']; // Get the country code
    return WC()->countries->countries[ $country ]; // return the country name

}

Code goes in function.php file of your active child theme (or active theme). Tested and works.


USAGE

You will add the following code in your child theme's header.php file:

1) in between html code:

<?php printf( '<p>' . __('We ship to %s', 'woocommerce') . '</p>', get_user_geo_country() ); ?>

2) or in between php code:

printf( '<p>' . __('We ship to %s', 'woocommerce') . '</p>', get_user_geo_country() );

Converting this to Shortcode:

function get_user_geo_country(){
    $geo      = new WC_Geolocation(); // Get WC_Geolocation instance object
    $user_ip  = $geo->get_ip_address(); // Get user IP
    $user_geo = $geo->geolocate_ip( $user_ip ); // Get geolocated user data.
    $country  = $user_geo['country']; // Get the country code
    return sprintf( '<p>' . __('We ship to %s', 'woocommerce') . '</p>', WC()->countries->countries[ $country ] );
}
add_shortcode('geoip_country', 'get_user_geo_country');

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Normal shortcode usage (in the backend text editor):

[geoip_country]

or in php code:

echo do_shortcode( "[geoip_country]" );
like image 98
LoicTheAztec Avatar answered Oct 19 '22 09:10

LoicTheAztec