仅在 WooCommerce 中显示特定地理位置国家/地区的产品价格

问题描述 投票:0回答:2

我已经使用 WooCommerce 开发了一个目录,但是由于我无法控制的原因,我需要能够 对从英国境外访问该网站的用户隐藏产品价格。

我找到了一些插件,可以让我根据访问者位置更改产品价格,但没有任何插件可以让我隐藏价格。

php wordpress woocommerce geoip product-price
2个回答
1
投票
有多种 Web API 可以为您提供帮助。例如

http://ipinfo.io

ip = $_SERVER['REMOTE_ADDR']; $details = json_decode(file_get_contents("http://ipinfo.io/{$ip}")); echo $details->country; // -> "US"

如果您必须进行许多检查,本地数据库会更好。 MaxMind 提供了一个

免费数据库,您可以将其与各种 PHP 库一起使用,包括GeoIP


0
投票
以下内容将

根据客户所在国家/地区隐藏英国以外的价格

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; }

此代码的更新版本可用

此答案避免后端错误。

我在启动时添加了功能:

if ( is admin() ) return $price;


代码位于活动子主题(或活动主题)的 function.php 文件中。已测试并有效。

© www.soinside.com 2019 - 2024. All rights reserved.