I’m using Apply a progressive discount based onWoocommerce cart total weight answer code (to my previous question) to add volume discount based on total cart weight.
The code is perfect, but I would like to show a banner above the cart page (only cart) like the ‘Added to Cart’ message, which shows a message and the amount customers have to order more for the next discount rule.
Example message: “If you order for € 10,- extra you will receive a 10% discount”
I tried to find the right code for the message box, but couldn’t find the right one. I can only find wc_add_to_cart_message_html
, but I’m pretty sure this one is not the right one.
Sorry for all those questions, but I’m very new with PHP and would like to learn. Hope anyone can help.
Advertisement
Answer
Updated
You will have to replace all your related code by the following that will make a discount based on cart weight, displaying a custom message displaying the remaining weight to get a better percentage discount (percentage displayed).
For the message: As it’s a weight based discount, it’s not possible to display a remaining cost. Instead you can display the remaining weight required to get a better discount.
Here is the code:
add_action( 'woocommerce_cart_calculate_fees', 'shipping_weight_discount', 30, 1 ); function shipping_weight_discount( $cart ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; $cart_weight = $cart->get_cart_contents_weight(); $cart_subtotal = $cart->get_subtotal(); // Or $cart->subtotal; $percentage = 0; if ( $cart_weight >= 10 && $cart_weight < 30 ) { $percentage = 5; $remaining_weight = 30 - $cart_weight; $next_percent = 7.5; } elseif ( $cart_weight >= 30 && $cart_weight < 70 ) { $percentage = 7.5; $remaining_weight = 70 - $cart_weight; $next_percent = 10; } elseif ( $cart_weight >= 70 && $cart_weight < 130 ) { $percentage = 10; $remaining_weight = 130 - $cart_weight; $next_percent = 12.5; } elseif ( $cart_weight >= 130 && $cart_weight < 200 ) { $percentage = 12.5; $remaining_weight = 200 - $cart_weight; $next_percent = 15; } elseif ( $cart_weight >= 200 ) { $percentage = 15; $next_percent = false; } else { $next_percent = 5; $remaining_weight = 10 - $cart_weight; } // Apply a calculated discount based on weight if( $percentage > 0 ) { $discount = $cart_subtotal * $percentage / 100; $cart->add_fee( sprintf( __( 'Weight %s discount', 'woocommerce' ), $percentage.'%'), -$discount ); } if ( did_action( 'woocommerce_cart_calculate_fees' ) >= 2 ) return; // Display a custom message if ( is_cart() && $next_percent ) { wc_add_notice( sprintf( __("If you order for %s extra, you will receive a %s discount.", "woocommerce"), wc_format_weight($remaining_weight), $next_percent.'%' ), 'notice' ); } }
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Screenshot of the message displayed in cart: