仅当在Woocommerce中应用了优惠券时才允许购买特定产品 [英] Allow specific products to be purchase only if a coupon is applied in Woocommerce
问题描述
我正在woocommerce网站上工作,我试图限制仅在应用了优惠券的情况下才能购买产品,因此,如果不添加优惠券代码,则不应对其进行处理。用户必须输入优惠券代码才能订购该特定产品(并非在所有其他产品上订购)。
I am working on a woocommerce website and I am trying to restrict a product to be purchased only if a coupon is applied for it, so it should not be processed without adding a coupon code. User must enter a coupon code to be able to order this specific product (not on all other products).
我们将不胜感激。
推荐答案
对于已定义的产品,如果未应用优惠券,以下代码将不允许结帐,并显示错误消息:
For defined products, the following code will not allow checkout if a coupon is not applied, displaying an error message:
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
}
}
}
代码会进入您的活动子主题(或活动主题)的functions.php文件。经过测试并有效。
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
在结帐中:
这篇关于仅当在Woocommerce中应用了优惠券时才允许购买特定产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!