首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果在WooCommerce过滤器中为欧盟国家声明REST

如果在WooCommerce过滤器中为欧盟国家声明REST
EN

Stack Overflow用户
提问于 2021-09-29 06:45:44
回答 1查看 107关注 0票数 0

更新:通过在这个if语句中包装我的对象,它不会中断API调用:

代码语言:javascript
复制
if ( WC()->customer ) {
}

我使用一个插件,显示所有的价格相同,无论增值税在WooCommerce。这很有效--但我只需要对欧盟国家这样做。

插件有一个过滤器:

代码语言:javascript
复制
add_filter('wc_aelia_tdbc_keep_prices_fixed', function($keep_prices_fixed): bool {
    if() {
        $keep_prices_fixed = true;
    }    
    return $keep_prices_fixed;
});

到目前为止我得到的是:

代码语言:javascript
复制
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;
});

在前端,这很有效--它只适用于欧盟国家的统一价格。但是,它确实破坏了WooCommerce REST,但出现了一个错误:

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

我假设WC()->customer->get_billing_country()对象没有在API调用中被初始化。

在访问对象之前,如何检查该对象是否已初始化?

EN

回答 1

Stack Overflow用户

发布于 2021-09-29 07:50:19

默认情况下,Woocommerce不会在rest中加载用户会话数据以提高性能。为此,您需要初始化用户会话,然后获取客户信息。

代码语言:javascript
复制
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();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69371591

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档