[英]Issue when adding a product to cart programmatically
I'm not well-versed with wordpress, but I'm facing a weird issue when trying to programmatically add a product to the cart. 我对Wordpress并不熟悉,但是在尝试以编程方式将产品添加到购物车时,我遇到了一个奇怪的问题。
The flow is like this: 流程是这样的:
Customer views a product 客户查看产品
Customer can add an additional product to their cart by selecting a checkbox option 客户可以通过选择复选框选项将其他产品添加到他们的购物车中
The item and an additional item should get added to the cart if the checkbox is confirmed checked 如果确认此复选框为选中状态,则该项目和其他项目应添加到购物车中
// product_extra_item_checkbox.php
add_action('woocommerce_before_add_to_cart_button', 'product_extra_item_checkbox');
add_action('woocommerce_add_to_cart', 'add_additional_item_to_cart');
function product_extra_item_checkbox () {
echo "
<input id='_add_additional_item' type='checkbox' class='checkbox add_item' value='1' name='_add_additional_item' />
";
}
function add_additional_item_to_cart () {
global $woocommerce;
if (isset($_POST['_add_additional_item'])) {
$productId = 59;
$woocommerce->cart->add_to_cart($productId);
echo "<script>alert('ADDED ADDITIONAL PRODUCT TO CART!!!');</script>"; // debug
}
}
I did get some complaints from xdebug saying the call stack was exceeded, so I guess it is relating to that, but I can't for the life of me figure out why the entire site crashes when I'm just trying to do something millions have done before (I've found examples as Wordpress is not my strong side). 我确实收到xdebug的一些抱怨,说超出了调用堆栈,所以我想这与之有关,但是我无法终生弄清楚为什么当我只是想做几百万个事情时整个站点崩溃了之前已经做过(我发现示例,因为Wordpress不是我的强项)。
Is it a limitation with my dev-environment, or am I doing something really wrong? 是我的开发环境的限制,还是我做错了什么?
Edit: I have disabled xdebug in my development environment, but the site crashes. 编辑:我在开发环境中禁用了xdebug,但是该站点崩溃了。
I've tested some more and got another error message: 我进行了更多测试,并收到另一条错误消息:
Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 20480 bytes) in .../wp-includes/taxonomy.php on line 1989
致命错误:1989年在线... / wp-includes / taxonomy.php中的536870912字节已用尽的内存大小(尝试分配20480字节)
seems to only be related to $woocommerce->cart->add_to_cart($productId);
似乎只与
$woocommerce->cart->add_to_cart($productId);
. 。
Solution? 解?
Well, logical errors happen, and it was actually just my own stupidity which resulted in the stack overflow ;)
. 好吧,发生逻辑错误,实际上是我自己的愚蠢导致了堆栈溢出
;)
。
Infinite loop caused because the system kept firing woocommerce_add_to_cart
action (which is to be expected) and $_POST['_add_additional_item']
was never cleaned up. 由于系统不断触发
woocommerce_add_to_cart
操作(这是可以预期的),并且从未清除$_POST['_add_additional_item']
而导致无限循环。
function add_additional_item_to_cart () {
global $woocommerce;
if (isset($_POST['_add_additional_item'])) {
unset($_POST['_add_additional_item']); // this fixed it
$productId = 59;
$woocommerce->cart->add_to_cart($productId);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.