您可以通过这种方式基于WC_Geolocation Class 制作自定义函数:
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
}
代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。
用法
您将在子主题的header.php 文件中添加以下代码:
1) 在 html 代码之间:
<?php printf( '<p>' . __('We ship to %s', 'woocommerce') . '</p>', get_user_geo_country() ); ?>
2) 或者在php代码之间:
printf( '<p>' . __('We ship to %s', 'woocommerce') . '</p>', get_user_geo_country() );
将其转换为简码:
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');
代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。
正常的短代码用法(在后端文本编辑器中):
[geoip_country]
或在php代码中:
echo do_shortcode( "[geoip_country]" );