In my attempt to find a solution for dollar amount based automatic coupon I am encountering the following problem. First the rules:
- If dollar amount less than 53 do nothing.
- If dollar amount greater than 53 and less than 90 apply "couponX"
- If dollar amount greater than 90 apply "couponY"
I have been able to get the code to work with the second (2) rule of the code. However the third rule will not be applied. My code below. Any thoughts?
// Add coupon when user views cart before checkout
add_action('woocommerce_before_cart_table', 'add_coupon_automatically');
add_action('woocommerce_before_checkout_form', 'add_coupon_automatically');
// Check if function? create it.
if (!function_exists('add_coupon_automatically')) {
function add_coupon_automatically() {
global $woocommerce;
$eleven = '20plus';
$four = '10plus';
$eleven_minimum = 179;
$four_minimum = 89;
if($woocommerce->cart->get_cart()->cart_contents_total>$eleven_minimum) {
// Apply 20plus
if (!$woocommerce->cart->add_discount( sanitize_text_field( $eleven )))
$woocommerce->add_message('20 Plus coupon (11%) automatically applied!');
$woocommerce->show_messages();
//Recalculate totals
$woocommerce->cart->calculate_totals();
} elseif ($woocommerce->cart->get_cart()->cart_contents_total<$eleven_minimum
&& $woocommerce->cart->get_cart()->cart_contents_total>$four_minimum) {
// Apply 10plus
if (!$woocommerce->cart->add_discount( sanitize_text_field( $four )))
$woocommerce->add_message('10 Plus coupon (4%) automatically applied!');
$woocommerce->show_messages();
//Recalculate totals
$woocommerce->cart->calculate_totals();
}
}
}