在 Woocommerce 中仅显示特定客户所在国家/地区的价格

Show prices only for a specific customer's country in Woocommerce

我已经使用 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;
}

An updated version of this code is available avoiding a backend bug.

I have added in the function on start:

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 that you can use with various PHP libraries, including GeoIP.