9

I'm working on using the wc() function in woocommerce. The documentation says it Returns the main instance of WC to prevent the need to use globals.

I can't find any examples of the use of this and I would like to know how to use wc() to do some basic things. I understand that it returns the main woocommerce instance; and from that I can extract all the data I would need; but I don't know the syntax for correct use ... might it be something like?

$foo = WC();
$bar = $foo->cart;
echo $bar;

could someone please correct this.

Also I am trying to understand what the advantages of doing it this way instead of globalizing variables.

byronyasgur
  • 4,627
  • 13
  • 52
  • 96

2 Answers2

17

as what the doc in your link says. 'prevent the need to use globals'. An example would be like this...

code using global.

global $woocommerce;
$customer_country = $woocommerce->customer->get_country();

code not using global

$customer_country = WC()->customer->get_country(); 
// some servers may not like like this... best is to use variables like $foo = WC(); then use $foo->customer->get_country()...

How to use WC() ? start here...

why must I avoid global?

Community
  • 1
  • 1
Reigel Gallarde
  • 64,198
  • 21
  • 121
  • 139
  • Wow a lot easier than I thought, thanks, that all makes perfect sense – byronyasgur Mar 16 '15 at 14:22
  • 1
    Not related to the original question, but why do people always write it as `WC()` not `wc()`. Any reason? – Fahmi Feb 08 '18 at 02:58
  • 1
    @tfont did you mean `wc` ? It's written in lowercase in the source code. – Fahmi Mar 24 '18 at 12:03
  • 2
    @Fahmi Now you made me do a bit of research! And version 3.2.6 has WC() but version 3.4.0 has wc(). Documentation uses wc but their URL has WC... in a nutshell, seems like they're being used in a exchangeable matter. it doesn't matter since PHP isn't case sensitive. https://docs.woocommerce.com/wc-apidocs/function-WC.html – tfont Mar 27 '18 at 08:30
  • 1
    interesting - i didnt know php isnt case sensitive. – ewizard Oct 30 '18 at 13:03
-1

WC() is just a function that returns an instance of the woocommerce class.

1) make sure you include the reference to the file where the function is located (see how to do that here) :

include_once WP_PLUGIN_DIR .'/woocommerce/woocommerce.php';

2) once you have that you can just add a local variable pointing to the current woocommerce instance:

$myWC = WC();

$myWC->cart->calculate_fees();
Hugo R
  • 2,613
  • 1
  • 14
  • 6
  • It's unlikely you will need to include woocommerce.php unless you are doing something very specialized - e.g. custom ajax implemenation – Zakalwe Jun 14 '21 at 17:28