问题描述
根据 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、summer 4和summer5,否则将无法结帐。我希望客户可以使用 target_id 数组中列出的任何产品的任何优惠券进行结账。
换句话说,对于所有产品,优惠券的使用是强制性的,但不一定是特定的优惠券,可以是代码中列出的任何一种。
例如,我列出了 5 个产品和 5 个优惠券,但实际上有 100 个产品和 100 个优惠券
提前致谢
解决方法
您的代码中有一些错误,请改用以下内容:
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 文件中。经测试有效。