基于WooCommerce中的访客位置后端错误隐藏价格



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

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

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中致电in in in in in in in in in in in /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/Admin/list-tables/list-tables/abstract-class-class-class-wc-admin-list-table.php (261): wc in /var/sites/o/oxfordriderwear.com/public_html/wp-content/themes/storefront/functions.php 在第61行

我使用过的代码中是否有一些不正确的内容,或者我需要添加的东西来解决此问题,以使我的管理区域如正常显示吗?

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

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文件中。测试并起作用。

没有更多错误。

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

最新更新