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

时间:2019-02-28 08:49:31

标签: php wordpress woocommerce geolocation price

我已经使用woocommerce开发了目录,但是由于我无法控制的原因,我需要能够隐藏来自英国以外访问该网站的用户的产品价格

我找到了可以让我根据访问者的位置更改产品价格的插件,但是没有什么可以隐藏价格。

有没有我想念的插件或可以添加到woocommerce文件中的任何东西来实现这一目标?

2 个答案:

答案 0 :(得分: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提供了free database,可以与各种PHP库一起使用,包括GeoIP

答案 1 :(得分: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;
}
  

on this answer提供了此代码的更新版本,避免了后端错误。

     

我已经在开始时添加了功能:

if ( is admin() ) return $price;

代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试,可以正常工作。