我如何在 woocommerce 中使用 wc()?

How do I use wc() in woocommerce?

我正在研究如何在 woocommerce 中使用 wc() 功能。 The documentationReturns the main instance of WC to prevent the need to use globals.

我找不到任何使用它的例子,我想知道如何使用 wc() 做一些基本的事情。我知道它 returns 主要的 woocommerce 实例;从中我可以提取我需要的所有数据;但我不知道正确使用的语法......可能是这样的?

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

有人可以更正这个吗。

另外,我正在尝试了解以这种方式而不是全球化变量的优势是什么。

正如您 link 中的文档所说。 'prevent the need to use globals'。一个例子是这样的...

使用全局代码。

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

代码未使用全局

$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()...

如何使用 WC() ? start here...

why must I avoid global?

WC() 只是一个函数,returns woocommerce class 的一个实例 class。

1) 确保包含对函数所在文件的引用(参见如何操作 ):

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

2) 一旦你有了它,你就可以添加一个指向当前 woocommerce 实例的局部变量:

$myWC = WC();

$myWC->cart->calculate_fees();