'wordpress function breaks wp-admin

I've created a function in my custom WooCommerce site. This works great on the frontend, but wp-admin breaks. Wp-admin shows a http-500 error.

This is the function:

// Set currency based on visitor country
 
function geo_client_currency($client_currency) {
        $country = WC()->customer->get_shipping_country();
           switch ($country) {
            case 'GB': return 'GBP'; break;
            default: return 'EUR'; break;
        }
}
add_filter('wcml_client_currency','geo_client_currency');

I've set the wp-debug on true and it will throw this message:

Fatal error: Uncaught Error: Call to a member function get_shipping_country() on null in

So it has to do something with: $country = WC()->customer->get_shipping_country(); but I can't find it. What is my mistake?



Solution 1:[1]

The customer property isn't set to an instance of WC_Customer in the backend so you can't call the get_shipping_country() method.

Check customer isn't null (default) before using it.

function geo_client_currency( $client_currency ) {
    if ( WC()->customer ) {
        $country = WC()->customer->get_shipping_country();

        /**
         * Assuming more are going to be added otherwise a switch is overkill.
         * Short example: $client_currency = ( 'GB' === $country ) ? 'GBP' : 'EUR';
         */
        switch ( $country ) {
            case 'GB': 
                $client_currency = 'GBP'; 
                break;

            default: 
                $client_currency = 'EUR';
        }
    }

    return $client_currency;
}
add_filter( 'wcml_client_currency', 'geo_client_currency' );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nathan Dawson