I'm trying to apply a percentage discount based on the number of products in the cart with a specific product attribute.
More precisely, my goal is to apply a 15% discount when purchasing at least 6 products with attribute "flaske".
I've successfully achieved this on products with variable properties set, but I can't seem to do it for a single/simple product.
This is my code so far (borrowed from WooCommerce for quantity and price conditions)
// 根据购物车中的产品数量和属性进行折扣。 add_action( 'woocommerce_cart_calculate_fees','wc_cart_item_quantity_discount' ); function wc_cart_item_quantity_discount( $cart ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; // 初始化变量。 $min_item_amount = 6; // 最小数量。 $discount = $items_count = $percent = $items_subtotal = 0; $taxonomy = 'pa_variant'; // 分类 $term_slugs = array('flaske'); // 术语 // 遍历购物车中的物品 foreach( $cart->get_cart() as $cart_item_key => $cart_item ) { // 遍历变体 foreach( $cart_item['variation'] as $attribute => $term_slug ) { // 只计算具有属性且数量超过6的物品。 if( $cart_item['data']->get_price() >= $min_item_amount && $attribute === 'attribute_'.$taxonomy && in_array( $term_slug, $term_slugs ) ) { $items_count += $cart_item['quantity']; $items_subtotal += $cart_item['line_subtotal']; } } } // 条件百分比。 if ($items_count >= 6 ) { $percent = 15; } // 折扣(应税)。 if( $items_count > 0 ) { // 计算 $discount -= ($items_subtotal / 100) * $percent; $cart->add_fee( __( "Mix & Match rabat - $percent%", "woocommerce" ), $discount, true); } }
My current code works great for variable products (variations) but seems to work for single products It has no effect, even if I give the single product the same properties as the variable product.
I suspect this has something to do with the foreach loop, i.e. foreach( $cart_item['variation'] as $attribute => $term_slug ).
How can I make it work in general so that it also works for a single/simple product with the same attribute "flaske"?
Thank you very much for your help and suggestions.
Offer Woocommerce percentage discount for each item based on quantity
Exclude variants with 2 specific attribute terms in Woocommerce, coupons are not available
This should work