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:
For example:
I have 3 categories:
- Category 1 -> Discount 20%
- Category 2 -> Discount 10%
- Category 3 -> Discount 5%
If I add a product from category 1, I would have to get the discount selected from that category.
And if I add a product from category 2, then the discount from that category applies.
The problem comes when you have products from different categories in the cart:
For example:
- Product A -> Category 1
- Product B -> Category 2
- Product C -> Category 1
- Product D -> Category 3
Below the subtotal, I would have to add the discount grouped by categories and give me the discount for all the products in that category:
For example:
- Discount Category 1 -> The percentage of all products in Category 1
- Discount Category 2 -> The percentage of all products in Category 2
- Discount Category 3 -> The percentage of all products in Category 3
I have been looking at tutorials and found this page where it shows a code to add certain functionality within “woocommerce_cart_calculate_fees”
https://wpfactory.com/blog/how-to-add-cart-fees-in-woocommerce-with-php/
I have tried to make this code on my own, but it does not group the categories as I put in the examples, but rather it shows me the percentage of the product that I have in the cart, so all the products appear for each line without grouping.
I would like it to appear by group of categories, and to show me the total of all the products added to that category.
If anyone can help me modify the code or make a new code with the examples I have given, I would appreciate it. Thanks
My code:
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' => 20,
'cat2' => 10,
'cat3' => 5,
);
foreach ( $cart->get_cart() as $cart_item_key => $values ) {
$product_categories = get_the_terms( $values['product_id'], 'product_cat' );
if ( $product_categories && ! is_wp_error( $product_categories ) ) {
$product_categories = wp_list_pluck( $product_categories, 'slug' );
foreach ( $product_categories as $product_category ) {
if ( ! empty( $fees[ $product_category ] ) ) {
$amount = $fees[ $product_category ];
$price = get_post_meta($values['product_id'] , '_price', true);
$tax = get_post_meta($values['product_id'] , '_tax_class', true);
$name = 'Discount ('.$amount.'%): ' . get_the_title( $values['product_id'] );
$discount = $price * ($amount / 100);
$taxable = false;
$tax_class = '$tax';
$cart->add_fee( $name, -$discount, $taxable, $tax_class );
}
}
}
}
}
}