基于Make coupon field mandatory for a product category in WooCommerce的答案,我试图在woocommerce实现特定产品的强制优惠券。
下面是我的代码尝试:
add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_for_specific_items' );
function mandatory_coupon_for_specific_items() {
$targeted_ids = array(40, 41, 42, 43, 44); // The targeted product ids (in this array)
$coupon_code = 'summer1, summer2, summer3, summer4, summer5'; // The required coupon code
$coupon_applied = in_array( strtolower($coupon_code), WC()->cart->get_applied_coupons() );
// Loop through cart items
foreach(WC()->cart->get_cart() as $cart_item ) {
// Check cart item for defined product Ids and applied coupon
if( in_array( $cart_item['product_id'], $targeted_ids ) && ! $coupon_applied ) {
wc_clear_notices(); // Clear all other notices
// Avoid checkout displaying an error notice
wc_add_notice( sprintf( 'The product"%s" requires a coupon for checkout.', $cart_item['data']-
>get_name() ), 'error' );
break; // stop the loop
}
}
}
代码完美地使优惠券成为强制性的,但我需要一个产品可以签出仅使用其中一张优惠券。
如果我将产品ID 40添加到购物车中,必须添加5张优惠券,summer1,summer2,summer3,summer3 4和summer5,否则结帐将是不可能的。我希望客户可以使用targeted_id数组中列出的任何产品的任何优惠券进行结帐。
换句话说,对于所有产品,优惠券的使用是强制性的,但不一定是特定的优惠券,可以是代码中列出的任何人。
例如,我列出了5种产品和5种优惠券,但实际上有100种产品和100种优惠券。
提前谢谢你
发布于 2021-02-24 18:03:21
代码中有一些错误,请使用以下代码:
add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_for_specific_items' );
function mandatory_coupon_for_specific_items() {
$targeted_ids = array(40, 41, 42, 43, 44); // The targeted product ids (in this array)
$coupon_codes = array('summer1', 'summer2', 'summer3', 'summer4', 'summer5'); // Array of required coupon codes
$coupons_found = array_intersect( array_filter( array_map( 'sanitize_title', $coupon_codes) ), WC()->cart->get_applied_coupons() );
// Loop through cart items
foreach(WC()->cart->get_cart() as $item ) {
// Check cart item for defined product Ids and applied coupon
if( in_array( $item['product_id'], $targeted_ids ) && empty($coupons_found) ) {
wc_clear_notices(); // Clear all other notices
// Avoid checkout displaying an error notice
wc_add_notice( sprintf( 'The product"%s" requires a coupon for checkout.', $item['data']->get_name() ), 'error' );
break; // stop the loop
}
}
}
代码位于活动子主题(或活动主题)的functions.php文件中。测试和工作。
https://stackoverflow.com/questions/66355212
复制相似问题