特定Woocommerce产品类别项目的强制性优惠券代码 [英] Mandatory Coupon code for specific Woocommerce product category items
问题描述
在Woocommerce中,我试图为特定类别的所有产品强制设置优惠券代码。
In Woocommerce, I'm trying to make a Coupon Code mandatory for all Products from a specific Category.
以下代码(放置在functions.php中)效果很好,但是无论产品类别如何,所有产品都必须使用优惠券代码:
The following code (placed in functions.php) works well, but makes Coupon Codes mandatory for all Products regardless of the product category:
add_action('woocommerce_check_cart_items', 'make_coupon_code');
function make_coupon_code()
{
global $woocommerce;
if(is_cart() || is_checkout()){
$my_coupon = $woocommerce->cart->applied_coupons;
echo $woocommerce->cart->get_applied_coupons;
if(empty($my_coupon))
{
wc_add_notice( '<strong>' . $btn['label'] . '</strong> ' . __( 'insert coupon code', 'woocommerce' ), 'error' );
}
}
}
有什么想法吗?
(我要定位的产品类别是'chef-masterclass')
推荐答案
已更新:下面的代码将防止结帐需要用于特定产品类别的强制性优惠券代码:
Updated: The code below will prevent checkout for a mandatory coupon code that need to be applied for a specific product category:
add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_code' );
function mandatory_coupon_code() {
// HERE below -- Your settings
$mandatory_coupon = 'summer'; // <== Coupon code
$product_categories = array( 'chef-masterclass' ); // <== Product category (Id, slug or name)
$applied_coupons = WC()->cart->get_applied_coupons();
// If coupon is found we exit
if( in_array( $mandatory_coupon, $applied_coupons ) ) return;
$found = false;
// Loop through cart items to check for the product category
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
}
}
// Coupon not applied and product category found
if( $found ){
// Display an error notice preventing checkout
$coupon_html = '<strong>"' . ucfirst( $mandatory_coupon ) . '"</strong>';
$message = sprintf( __( 'Please enter the coupon code %s to checkout.', 'woocommerce' ), $coupon_html );
wc_add_notice( $message, 'error' );
}
}
代码会出现在您活跃孩子的function.php文件中主题(或活动主题)。经过测试并有效
Code goes in function.php file of your active child theme (or active theme). Tested and works
这篇关于特定Woocommerce产品类别项目的强制性优惠券代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!