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

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

在我的上一个问题中,我问过如何向英国以外的访客隐藏价格。

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

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

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

致命错误:未捕获错误:在/var/sites/o/oxfordriderwear.com/public_html/wp-content/themes/storefront/functions.php:61中调用null上的成员函数get_billing_country()堆栈跟踪:#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-第61行的content / themes / storefront / functions.php

在我使用的代码中是否有不正确的东西,或者我需要添加一些东西来修复此问题,以便我的管理区域显示正常?

php wordpress woocommerce orders customer
2个回答
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文件中。经过测试和工作。

没有更多的bug。


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;
}
© www.soinside.com 2019 - 2024. All rights reserved.