Referring to this question: Apply a coupon programmatically in Woocommerce and then this one:How to apply an automatic discount in WooCommerce based on cart total?
Complete rookie here. I need to auto-apply an already existing coupon to one particular product when the subtotal of other products in the cart is $40. And I need to make sure that applying the discount doesn't create a loop by taking the coupon out due to dropping the total below the $40 threshold.
I'm not sure how to modify this code to do that:
add_action('woocommerce_before_checkout_process','add_discount_at_checkout');
function add_discount_at_checkout(){
global $woocommerce;
$minorder = 99;
if( $woocommerce->cart->get_cart()->cart_contents_total>$minorder){
//APPLY COUPON HERE
}
}
First the targeted coupon code need to be set as restricted to the targeted product only:
The following code will apply a specific coupon (a discount) just to a specific cart item if the cart subtotal (excluding this specific cart item) is up to $40
:
add_action('woocommerce_before_calculate_totals', 'discount_based_on_total_threshold');
function discount_based_on_total_threshold( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Your settings
$coupon_code = 'summer'; // Coupon code
$amount_threshold = 40; // Total amount threshold
$targeted_product = 37; // Targeted product ID
// Initializing variables
$total_amount = 0;
$applied_coupons = $cart->get_applied_coupons();
$coupon_code = sanitize_text_field( $coupon_code );
$found = false;
// Loop through cart items
foreach( $cart->get_cart() as $cart_item ) {
if( ! in_array( $targeted_product, array( $cart_item['product_id'], $cart_item['data']->get_id() ) ) ) {
// Get the cart total amount (excluding the targeted product)
$total_amount += $cart_item['line_total'] + $cart_item['line_tax'];
} else {
// Targeted product is found
$found = true;
}
}
// Applying coupon
if( ! in_array($coupon_code, $applied_coupons) && $found && $total_amount >= $amount_threshold ){
$cart->add_discount( $coupon_code );
}
// Removing coupon
elseif( in_array($coupon_code, $applied_coupons) && ( $total_amount < $amount_threshold || ! $found ) ){
$cart->remove_coupon( $coupon_code );
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.