Get user geolocated country name in Woocommerce 3

二次信任 提交于 2020-01-01 03:37:07

问题


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


来源:https://stackoverflow.com/questions/51275007/get-user-geolocated-country-name-in-woocommerce-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!