我想使用WooCommerce优惠券功能添加10%的折扣,只有当客户从3个不同的产品类别(如类别1,类别2,类别3(购买产品时。
如何使用WooCommerce优惠券功能完成此操作?
对此的任何帮助将不胜感激。
更新说明:我只有 3 个父产品类别,没有子类别。每个产品都分配到一个类别。有些产品是可变的,有些则很简单。
这是一个不使用我从上一个问题中回收的优惠券代码的解决方案。
add_action( 'woocommerce_cart_calculate_fees' , 'add_multiple_category_discount' );
function add_multiple_category_discount( $cart ){
if( $cart->cart_contents_count < 3 ){
return;
}
$product_cats = array();
foreach( $cart->get_cart() as $item ) {
$product = wc_get_product( $item['product_id'] );
foreach( $product->get_category_ids() as $key => $cat_id ) {
if( ! in_array( $cat_id, $product_cats ) )
$product_cats[] = $cat_id;
}
}
// If we have 3 distinct categories then apply a discount
if( count( $product_cats ) >= 3 ) {
// Add a 10% discount
$discount = $cart->subtotal * 0.1;
$cart->add_fee( 'You have 3 different product categories in your cart, a 10% discount has been added.', -$discount );
}
}
要使用优惠券处理此功能,您需要按产品设置一个产品类别或按产品设置一个父类别,因为一个产品可以为其设置多个类别和子类别。
当购物车商品来自 3 个不同的产品类别时,此自定义函数将添加优惠券折扣。如果购物车商品从购物车中删除,并且不再有 3 个不同的产品类别,优惠券代码将自动删除。
此外,您还需要在函数中设置优惠券代码名称和所有匹配产品类别ID的数组。
这是代码:
add_action( 'woocommerce_before_calculate_totals', 'add_discount_for_3_diff_cats', 10, 1 );
function add_discount_for_3_diff_cats( $wc_cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// HERE set your coupon code and your parent product categories in the array
$coupon_code_to_apply = 'summer';
// HERE define your product categories IDs in the array
$your_categories = array( 11, 13, 14 ); // IDs
// If coupon is already set
if( $wc_cart->has_discount( $coupon_code_to_apply ) )
$has_coupon = true;
foreach( $wc_cart->get_cart() as $cart_item ) {
$product_id = $cart_item['product_id'];
$product = wc_get_product($product_id);
foreach( $product->get_category_ids() as $category_id ) {
if( has_term( $your_categories, 'product_cat', $product_id ) && in_array( $category_id, $your_categories ) ){
// Set the categories in an array (avoiding duplicates)
$categories[$category_id] = $category_id;
}
}
}
$count_cats = count($categories);
$has_discount = $wc_cart->has_discount( $coupon_code_to_apply );
if ( 3 <= $count_cats && ! $has_discount ) {
$wc_cart->add_discount($coupon_code_to_apply);
} elseif ( 3 > $count_cats && $has_discount ) {
$wc_cart->remove_coupon($coupon_code_to_apply);
}
}
代码进入函数.php活动子主题(或主题(的文件或任何插件文件中。
经过测试,适用于简单和可变的产品...