【发布时间】:2019-09-12 09:19:34
【问题描述】:
当购物车总数超过一定数量时,我正在使用以下代码将免费产品添加到购物车中。
当我低于购物车总数时,它会触发 if 语句,但不会删除产品。
我认为这可能是因为购物篮表单上的数量设置为 1,而我的代码没有覆盖该数量以将其设置为 0(并将其删除)。
还有其他方法可以删除或覆盖它吗?
/*
* Automatically adding the product to the cart when cart total amount reach to £20.
*/
function aapc_add_product_to_cart() {
global $woocommerce;
$cart_total = 20;
$free_product_id = 85028; // Product Id of the free product which will get added to cart
if ( $woocommerce->cart->total >= $cart_total ) {
echo "Over the limit";
$quantity = 1;
WC()->cart->add_to_cart( $free_product_id, $quantity );
} elseif($woocommerce->cart->total < $cart_total) {
echo "Under the limit";
$quantity = 0;
WC()->cart->remove_cart_item( $free_product_id, $quantity );
}
}
add_action( 'template_redirect', 'aapc_add_product_to_cart' );
我尝试过使用这个question,但无法让它发挥作用,它甚至无法将商品添加到我的购物篮中。
如果有帮助,我正在使用 Woocommerce 版本 3.6.5。
【问题讨论】:
-
在您的情况下,似乎有一些麻烦,因为 linked answer thread 在上一个 Woocommerce 版本上仍然可以完美运行。它可以是您、您的主题或插件进行的另一种定制。
template_redirect钩子不适用于 Ajax 迷你购物车操作(删除)或 Ajax 购物车页面操作(更改数量、删除),因为它适用于页面加载。钩子woocommerce_before_calculate_totals或woocommerce_calculate_totals很方便,因为它们启用了 Ajax。 -
@LoicTheAztec 刚刚让它适用于购物篮页面,不知道为什么链接的答案不起作用,但确实如此(请参阅我的答案)。我可能有链接的答案来覆盖 ajax 部分......所以我对篮子的修复和你对 ajax 部分的答案?
-
当使用
woocommerce_before_calculate_totals钩子时你不能使用cart->total(因为它不显示任何东西)。相反,您需要使用cart->subtotal...这是我认为的主要问题。
标签: php woocommerce