I need help with a code for Woocommerce.
I need to add a discount for each selected category in each product, and group it by each category.
They made me this code, which makes everything correct but the only thing I need is to have the quantities.
When a product has one quantity, the discount works for me, but when you add another quantity and it has two quantities, the same product does not count the quantities in the cart.
Can someone help me modify this code so that it counts the quantities of each product? Thanks
add_action( 'woocommerce_cart_calculate_fees', 'wpf_wc_add_cart_fees_by_product_category' );
if ( ! function_exists( 'wpf_wc_add_cart_fees_by_product_category' ) ) {
function wpf_wc_add_cart_fees_by_product_category( $cart ) {
$fees = array(
'cat1' => 10,
'cat2' => 5,
'cat3' => 3,
);
// Initialize an array to store the discounts grouped by category
$category_discounts = array();
// Loop through the cart items
foreach ( $cart->get_cart() as $cart_item_key => $values ) {
$product_id = $values['product_id'];
$product_price = $values['data']->get_price();
$product_categories = get_the_terms( $product_id, 'product_cat' );
// Check if the product has categories and there is no error
if ( $product_categories && ! is_wp_error( $product_categories ) ) {
foreach ( $product_categories as $product_category ) {
$category_slug = $product_category->slug;
// Check if the category has a defined discount
if ( ! empty( $fees[ $category_slug ] ) ) {
$discount_percentage = $fees[ $category_slug ];
$discount_amount = $product_price * ($discount_percentage / 100);
// Accumulate the discount for the category
if ( ! isset( $category_discounts[ $category_slug ] ) ) {
$category_discounts[ $category_slug ] = 0;
}
$category_discounts[ $category_slug ] += $discount_amount;
}
}
}
}
// Add the accumulated discounts as fees in the cart
foreach ( $category_discounts as $category_slug => $discount_amount ) {
$category_name = get_term_by( 'slug', $category_slug, 'product_cat' )->name;
$fee_name = 'Discount (' . $fees[$category_slug] . '%): ' . $category_name;
$cart->add_fee( $fee_name, -$discount_amount, false );
}
}
}