根据Woocommerce中的访客位置后端错误隐藏价格

时间:2019-02-28 11:34:50

标签: php wordpress woocommerce orders customer

在最后一个问题中,我问如何向英国以外的游客隐藏价格。

基于答案,我成功使用了此代码

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

这可以按预期工作,但是当我尝试在管理区域中编辑产品时,在每个产品的价格列中都会出现此错误:

  

致命错误:未捕获错误:在null中调用成员函数get_billing_country()   /var/sites/o/oxfordriderwear.com/public_html/wp-content/themes/storefront/functions.php:61   堆栈跟踪:#0   /var/sites/o/oxfordriderwear.com/public_html/wp-includes/class-wp-hook.php(286):   country_geolocated_based_hide_price('apply_filters('get_price_html()#4   /var/sites/o/oxfordriderwear.com/public_html/wp-content/plugins/woocommerce/includes/admin/list-tables/abstract-class-wc-admin-list-table.php(261):   WC in   /var/sites/o/oxfordriderwear.com/public_html/wp-content/themes/storefront/functions.php   在第61行

我使用的代码中是否存在某些错误,或者我需要添加一些内容来解决此问题,以便我的管理区域正常显示?

2 个答案:

答案 0 :(得分:1)

为避免此问题,我们可以在后端使用以下格式返回格式化的价格:

add_filter( 'woocommerce_get_price_html', 'country_geolocated_based_hide_price', 10, 2 );
function country_geolocated_based_hide_price( $price, $product ) {
    // Not on backend
    if( is_admin() ) 
        return $price;

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

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

没有更多的错误。

答案 1 :(得分:0)

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 ) {
        $customer = WC_Customer(get_current_user_id());
        $country = $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;
}