【发布时间】:2020-10-26 11:41:11
【问题描述】:
我在 WooCommerce 网站上工作,我试图限制仅在为其申请优惠券的情况下购买产品,因此如果不添加优惠券代码,则不应对其进行处理。
用户必须输入优惠券代码才能订购此特定产品(并非所有其他产品)。
我们不需要它来定位特定的优惠券以允许结帐,我们需要它来要求任何优惠券,因为对于这个特定的产品,我们有大约 150 多张优惠券。
基于Allow specific products to be purchase only if a coupon is applied in Woocommerce代码线程:
add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_for_specific_items' );
function mandatory_coupon_for_specific_items() {
$targeted_ids = array(37); // The targeted product ids (in this array)
$coupon_code = 'summer2'; // 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
}
}
}
处理方法:如果购物车中的某些产品没有使用优惠券,则阻止结帐。
【问题讨论】:
标签: wordpress woocommerce product checkout coupon