我使用woocommerce开发了一个目录,但是由于我无法控制的原因,我需要能够隐藏从英国以外访问该网站的用户的产品价格。
我发现插件允许我根据访客位置更改产品价格,但没有什么可以让我隐藏价格。
有没有我错过的插件或我可以添加到woocommerce文件中的任何插件来实现这一目标?
以下将根据客户地理位置国家隐藏英国以外的价格:
add_filter( 'woocommerce_get_price_html', 'country_geolocated_based_hide_price', 10, 2 );
function country_geolocated_based_hide_price( $price, $product ) {
// Get an instance of the WC_Geolocation object class
$geo_instance = new WC_Geolocation();
// Get geolocated user geo data.
$user_geodata = $geo_instance->geolocate_ip();
// Get current user GeoIP Country
$country = $user_geodata['country'];
return $country !== 'GB' ? '' : $price;
}
代码位于活动子主题(或活动主题)的function.php文件中。经过测试和工作。
如果要仅为未记录的客户启用该地理定位功能,请使用以下命令:
add_filter( 'woocommerce_get_price_html', 'country_geolocated_based_hide_price', 10, 2 );
function country_geolocated_based_hide_price( $price, $product ) {
if( get_current_user_id() > 0 ) {
$country = WC()->customer->get_billing_country();
} else {
// Get an instance of the WC_Geolocation object class
$geo_instance = new WC_Geolocation();
// Get geolocated user geo data.
$user_geodata = $geo_instance->geolocate_ip();
// Get current user GeoIP Country
$country = $user_geodata['country'];
}
return $country !== 'GB' ? '' : $price;
}
这个代码的更新版本可用on this answer避免后端错误。
我在启动时添加了函数:
if ( is admin() ) return $price;
代码位于活动子主题(或活动主题)的function.php文件中。经过测试和工作。
有各种Web API可以帮助您。例如http://ipinfo.io
ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}"));
echo $details->country; // -> "US"
如果必须进行许多检查,则本地数据库更好。 MaxMind提供了一个free database,您可以使用各种PHP库,包括GeoIP。