Get user geolocated country name in Woocommerce 3

2019-03-21 17:16发布

问题:

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

I would like to Write an 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.

回答1:

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]" );