4

I want to unset some WooCommerce session variables because on page load the hooks I'm using haven't fired which leaves previous session data populating the checkout shipping table.

Within any functions accessed from the hook callbacks, I can access WooCommerce session vars like:

WC()->session->get('foo');

However, when outside of those callbacks, WC is undefined. I tried setting:

global $woocommerce; and accessing via $woocommerce->session->__unset('foo'); but got the notice:

Trying to get property of non-object

and the error:

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

So, clearly this $woocommerce global is not the same as WC (which I guess is exposed by the hooks?)

I think I can unset these variables using one of the first hooks that will fire on the checkout page, but it got me wondering:

What is the difference between WC() and $woocommerce? Aren't they both ways to access WooCommerce methods?

1 Answer 1

7

wc(); returns the singleton instance of WooCommerce to prevent the need to use globals.

WC sets the $woocommerce global this way: $GLOBALS['woocommerce'] = wc();, so using one or the other seems the same...

EDIT

About your errors, you got them because $woocommerce->session has not been set. WC initializes WC_Session_Handler only on frontend or CRON requests. Choose your action hook accordingly.

3
  • So were my errors caused by a syntax mistake? What's the right way to call the __unset() function on a session variable using the $woocommerce global? Commented Aug 5, 2017 at 15:48
  • @armadadrive, see my edit.
    – ClemC
    Commented Aug 5, 2017 at 16:20
  • This is awesome. One less step away from globals! Commented Mar 23, 2018 at 13:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.