我正在寻找一个Woocommerce挂钩,该挂钩将有助于在应用特定优惠券时根据2种不同的产品类别限制来更改折扣百分比。
例如,如果客户添加特定的优惠券,我想:
如果购物车商品来自产品类别A,则它将为该商品提供10%的折扣。 如果它属于产品类别B,则将对该商品给予20%的折扣
我找到了此代码,但仍可以从WooCommerce的Coupons中获得优惠券折扣。
add_filter( 'woocommerce_coupon_get_discount_amount', 'alter_shop_coupon_data', 20, 5 );
function alter_shop_coupon_data( $round, $discounting_amount, $cart_item, $single, $coupon ){
## ---- Your settings ---- ##
// Related coupons codes to be defined in this array (you can set many)
$coupon_codes = array('10percent');
// Product categories at 20% (IDs, Slugs or Names) for 20% of discount
$product_category20 = array('hoodies'); // for 20% discount
$second_percentage = 0.2; // 20 %
## ---- The code: Changing the percentage to 20% for specific a product category ---- ##
if ( $coupon->is_type('percent') && in_array( $coupon->get_code(), $coupon_codes ) ) {
if( has_term( $product_category20, 'product_cat', $cart_item['product_id'] ) ){
$original_coupon_amount = (float) $coupon->get_amount();
$discount = $original_coupon_amount * $second_percentage * $discounting_amount;
$round = round( min( $discount, $discounting_amount ), wc_get_rounding_precision() );
}
}
return $round;
}
答案 0 :(得分:0)
此挂钩获取已触发,您的购物车获取了更新。所以也许这是正确的钩子。尝试使代码适合于foreach。如果您需要更多帮助,请告诉我。
add_action( 'woocommerce_update_cart_action_cart_updated', 'on_action_cart_updated', 20, 1 );
function on_action_cart_updated( $cart_updated ) {
$applied_coupons = WC()->cart->get_applied_coupons();
if ( count( $applied_coupons ) > 0 ) {
foreach ( $applied_coupons as $coupon ) {
$round = .....
}
$cart_subtotal = WC()->cart->get_cart_subtotal();
$new_value = $cart_subtotal - $round;
WC()->cart->set_total( $new_value );
if ( $cart_updated ) {
// Recalc our totals
WC()->cart->calculate_totals();
}
}
}