简体   繁体   English

如果欧盟国家的 else 声明在 WooCommerce 的过滤器中中断 REST API

[英]If else statement for EU countries in filter for WooCommerce breaks REST API

Update: By wrapping my object in this if statement it doesn't break the API call:更新:通过将我的 object 包装在这个 if 语句中,它不会中断 API 调用:

if ( WC()->customer ) {
}

Im using a plugin that displays all prices the same regardless of VAT in WooCommerce. This works well - but I only need this for EU countries.我使用的插件显示所有价格相同,而不管 WooCommerce 中的增值税。这很好用 - 但我只需要欧盟国家/地区。

The plugin has a filter:该插件有一个过滤器:

add_filter('wc_aelia_tdbc_keep_prices_fixed', function($keep_prices_fixed): bool {
    if() {
        $keep_prices_fixed = true;
    }    
    return $keep_prices_fixed;
});

What I got so far:到目前为止我得到了什么:

add_filter('wc_aelia_tdbc_keep_prices_fixed', function($keep_prices_fixed): bool {
    
            $countries = new WC_Countries();
        $eu_countries = $countries->get_european_union_countries();
    
       if ( in_array( WC()->customer->get_billing_country(), $eu_countries ) ) {
        $keep_prices_fixed = true;
        } else {
        $keep_prices_fixed = false;
        }
    
    return $keep_prices_fixed;
});

On the front-end this works well - it only applies the flat prices for EU countries.在前端这很有效——它只适用于欧盟国家的统一价格。 It does however break the WooCommerce REST API with an error:然而,它确实打破了 WooCommerce REST API 并出现错误:

Uncaught Error: Call to a member function get_billing_country() on null

I assume the WC()->customer->get_billing_country() object is not being initialised in the API call.我假设WC()->customer->get_billing_country() object 未在 API 调用中初始化。

How do I check if this object are initialised, before accessing it?在访问之前,如何检查此 object 是否已初始化?

By default Woocommerce will not load user session data in rest api to improve the performance.默认Woocommerce不会加载rest api中的用户session数据,以提高性能。 For that you need to initialize the user session, then get the customer info.为此,您需要初始化用户 session,然后获取客户信息。

if ( null === WC()->session ) {
   $session_class = apply_filters( 'woocommerce_session_handler', 'WC_Session_Handler' );
    WC()->session = new $session_class();
    WC()->session->init();
}
WC()->customer = new WC_Customer( get_current_user_id(), true );
echo WC()->customer->get_billing_country();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM