在WooCommerce中将优惠券字段强制设置为产品类别 [英] Make coupon field mandatory for a product category in WooCommerce
本文介绍了在WooCommerce中将优惠券字段强制设置为产品类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在努力做到这一点,因此Woocommerce上的产品类别必须使用优惠券字段。我试图使用
I am trying to make it so the coupon field is mandatory on Woocommerce for a product category. I have tried to use the code from this answer but it only works with a set of coupon code. I need it to work with any valid coupon code.
Thank you for any help.
解决方案
Try the following that will make the coupon field mandatory when a cart item from a specific product category is found:
add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_code' );
function mandatory_coupon_code() {
// Set your product categories in the array (can be term IDs, slugs or names)
$product_categories = array( 'clothing' );
$found = false;
// Loop through cart items to check for the product categories
foreach ( WC()->cart->get_cart() as $cart_item ){
if( has_term( $product_categories, 'product_cat', $cart_item['product_id'] ) ){
$found = true; // cart item from the product category is found
break; // We can stop the loop
}
}
// If not found we exit
if( ! $found ) return; // exit
$applied_coupons = WC()->cart->get_applied_coupons();
// Coupon not applied and product category found
if( is_array($applied_coupons) && sizeof($applied_coupons) == 0 ) {
// Display an error notice preventing checkout
$message = __( 'Please enter a coupon code to be able to checkout.', 'woocommerce' );
wc_add_notice( $message, 'error' );
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works
这篇关于在WooCommerce中将优惠券字段强制设置为产品类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文