问题描述
当购物车中有产品ID 1362时,我会自动应用优惠券,但是当有人添加其他产品并删除1362时,该优惠券会继续使用,如果没有1362产品ID,如何通过移除优惠券来防止这种情况在带有Woocommerce的购物车中?
I am applying automatically a coupon when there is a product id 1362 in the cart, but when someone adds another product and delete the 1362 the coupon stays applied, how to prevent this by removing the coupon if there is no 1362 product id in the cart with Woocommerce ?
我知道我们可以将优惠券限制为一种产品,但我不希望这样,我希望将优惠券仅应用于所有购物车
I know we can restrict coupon to a product but i don't want this, i want my coupon to be applied to all products cart only if there is the product with id 1362 in this cart.
add_action( 'woocommerce_before_cart', 'bbloomer_apply_matched_coupons' );
function bbloomer_apply_matched_coupons() {
global $woocommerce;
$coupon_code = 'boxpersonnalisable';
if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;
foreach ( $woocommerce->cart->cart_contents as $key => $values ) {
// this is your product ID
$autocoupon = array( 1362 );
if( in_array( $values['product_id'], $autocoupon ) ) {
add_filter('woocommerce_coupon_message','remove_msg_filter',10,3);
$woocommerce->cart->add_discount( $coupon_code );
wc_print_notices();
}
}
}
非常感谢
推荐答案
这是在以下情况下使其工作的方法:
Here is the way to make it work when:
- 在将特定产品添加到购物车时添加特定的优惠券代码
- 在从购物车中移除特定产品时删除特定的应用优惠券代码
- (在两种情况下,您都可以显示自定义通知)…
- adding a specific coupon code when a specific product is added to cart
- removing a specific applied coupon code when a specific product is removed from cart
- (in both cases you can display a custom notice)…
代码:
add_action( 'woocommerce_before_calculate_totals', 'auto_add_remove_coupon' );
function auto_add_remove_coupon( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$coupon_code = 'boxpersonnalisable';
$targeted_product_ids = array( 1362 );
$found = false;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ){
if( in_array( $cart_item['product_id'], $targeted_product_ids ) ){
$found = true;
break;
}
}
if ( ! $cart->has_discount( $coupon_code ) && $found ) {
$cart->add_discount( $coupon_code );
wc_clear_notices();
wc_add_notice( __("Your custom notice - coupon added (optional)","woocommerce"), 'notice');
} elseif ( $cart->has_discount( $coupon_code ) && ! $found ) {
$cart->remove_coupon( $coupon_code );
wc_clear_notices();
wc_add_notice( __("Your custom notice - coupon removed (optional)","woocommerce"), 'notice');
}
}
代码会出现在您活跃孩子的function.php文件中主题(或活动主题)。经过测试并有效
Code goes in function.php file of your active child theme (or active theme). Tested and works
这篇关于自动针对特定产品ID在Woocommerce购物车中应用或删除优惠券的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!