简体   繁体   中英

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:

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.

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:

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.

How do I check if this object are initialised, before accessing it?

By default Woocommerce will not load user session data in rest api to improve the performance. For that you need to initialize the user session, then get the customer info.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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