Updated — Corrected code mistakes and added enhancements in the outputted discount text
Here is the function hooked in woocommerce_cart_calculate_fees
hook that is going to make the discount for that particular category (or subcategory too) based on cart item quantity calculations.
This is the code:
add_action( 'woocommerce_cart_calculate_fees', 'cart_items_quantity_wine_discount', 10, 1 );
function cart_items_quantity_wine_discount($cart_object) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Set HERE your category (can be an ID, a slug or the name)
$category = 34; // or a slug: $category = 'wine';
$category_count = 0;
$category_total = 0;
$discount = 0;
// Iterating through each cart item
foreach($cart_object->get_cart() as $cart_item):
if( has_term( $category, 'product_cat', $cart_item['product_id']) ):
$category_count += $cart_item['quantity'];
$category_total += $cart_item["line_total"]; // calculated total items amount (quantity x price)
endif;
endforeach;
$discount_text = __( 'Quantity discount of ', 'woocommerce' );
// ## CALCULATIONS ##
if ( $category_count >= 12 && $category_count < 24 ) {
$discount -= $category_total * 0.1; // Discount of 10%
$discount_text_output = $discount_text . '10%';
} elseif ( $category_count >= 24 && $category_count < 48 ) {
$discount -= $category_total * 0.15; // Discount of 15%
$discount_text_output = $discount_text . '15%';
} elseif ( $category_count >= 48 ) {
$discount -= $category_total * 0.2; // Discount of 20%
$discount_text_output = $discount_text . '20%';
}
// Adding the discount
if ( $discount != 0 && $category_count >= 12 )
$cart_object->add_fee( $discount_text_output, $discount, false );
// Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}
Note: Last argument in add_fee()
method is related to applying the tax or not to the discount…
Code is tested and fully functional.
Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.
Other similar: Discount for Certain Category Based on Total Number of Products
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…