Hi I’m looking to automatically apply a coupon discount of 20% to the cart when its total is â¬25 or more – I’ve looked at the code from a previous user and tried modifying it and placing it in the functions.php, however it doesn’t work for me – Any help as to what I’m doing wrong/? Here is the code I placed into functions.php;
/* Mod: 20% Discount for orders over â¬25
Works with code added to child theme: woocommerce/cart/cart.php lines 13 - 14: which gets $subtotal of cart:
global $subtotal;
$subtotal= $woocommerce->cart->subtotal;
*/
add_action('woocommerce_before_cart_table', 'discount_when_order_greater_25');
function discount_when_order_greater_25( ) {
global $woocommerce;
global $subtotal;
if( $subtotal >= 25 ) {
$coupon_code = '20';
if (!$woocommerce->cart->add_discount( sanitize_text_field( $coupon_code ))) {
$woocommerce->show_messages();
}
echo '<div class="woocommerce_message"><strong>Your order is over â¬25 so a 20% Discount has been Applied!</strong> Your total order weight is <strong>' . $total_weight . '</strong> lbs.</div>';
}
}
/* Mod: 20% Discount for orders under â¬25 */
add_action('woocommerce_before_cart_table', 'remove_discount_when_order_less_25');
function remove_discount_when_order_less_25( ) {
global $woocommerce;
global $subtotal;
if( $subtotal < 25 ) {
$coupon_code = '20';
$woocommerce->cart->get_applied_coupons();
if (!$woocommerce->cart->remove_coupons( sanitize_text_field( $coupon_code ))) {
$woocommerce->show_messages();
}
$woocommerce->cart->calculate_totals();
}
}
I’ve been having troubles with free WooCommerce plugins that are intended to do this (automatically apply a coupon code in the woo commerce cart).
Secondly, the forum posts I easily found on Google were incomplete and were throwing unhandled exceptions.
So here’s working code example as of today 2020-11-03. You can put this in your WordPress child theme’s folder functions.php file: