是的,这是真的,因为WooCommerce购物车仅在前端初始化(或者如果是前端请求):
但它失败了,因为$woocommerce->cart
始终为空。
所以在WooCommerce 3.6.4 (current release as of writing) or later, 您可以手动初始化购物车,如下所示:
// Load cart functions which are loaded only on the front-end.
include_once WC_ABSPATH . \'includes/wc-cart-functions.php\';
include_once WC_ABSPATH . \'includes/class-wc-cart.php\';
// wc_load_cart() does two things:
// 1. Initialize the customer and cart objects and setup customer saving on shutdown.
// 2. Initialize the session class.
if ( is_null( WC()->cart ) ) {
wc_load_cart();
}
所以你的
add_to_cart()
可能看起来是这样的:
function add_to_cart() {
defined( \'WC_ABSPATH\' ) || exit;
// Load cart functions which are loaded only on the front-end.
include_once WC_ABSPATH . \'includes/wc-cart-functions.php\';
include_once WC_ABSPATH . \'includes/class-wc-cart.php\';
if ( is_null( WC()->cart ) ) {
wc_load_cart();
}
// I\'m simply returning the cart item key. But you can return anything you want...
return WC()->cart->add_to_cart( 15 );
}
旧WooCommerce 3.6的注释。x版本,this article 可能对你有帮助。
正如您所看到的,上面的代码很简单(对我来说效果很好);但是,实际上您可以尝试现有的解决方案:CoCart.
您应该始终使用WC()
访问全球$woocommerce
变量/对象。
我想这只是问题中的一个输入错误:\'callback\' => [ \'add_to_cart\' ]
因为这会导致错误,应该是以下其中之一:
\'callback\' => \'add_to_cart\'
\'callback\' => [ $this, \'add_to_cart\' ]
\'callback\' => [ $my_class, \'add_to_cart\' ]
\'callback\' => [ \'My_Class\', \'add_to_cart\' ]