Reputation: 5846
I am currently developing a plugin for woocommerce, and have the following code which adds a discount code if the total of the cart is in between the 2 values:
add_action('woocommerce_before_cart', 'woobd_add_discount_if_enabled');
function woobd_add_discount_if_enabled()
{
global $woocommerce;
if ($woocommerce->cart->cart_contents_total >= 10
&& $woocommerce->cart->cart_contents_total <= 100
) {
$woocommerce->cart->add_discount('layer1_discount');
} else {
$woocommerce->cart->remove_coupons('layer1_discount');
$woocommerce->cart->calculate_totals();
}
}
The above works fine, however i would like to add another if statement like this which adds another 2 values:
add_action('woocommerce_before_cart', 'woobd_add_discount_if_enabled');
function woobd_add_discount_if_enabled()
{
global $woocommerce;
if ($woocommerce->cart->cart_contents_total >= 10
&& $woocommerce->cart->cart_contents_total <= 100
) {
$woocommerce->cart->add_discount('layer1_discount');
} else {
$woocommerce->cart->remove_coupons('layer1_discount');
$woocommerce->cart->calculate_totals();
}
if ($woocommerce->cart->cart_contents_total >= 100
&& $woocommerce->cart->cart_contents_total <= 200
) {
$woocommerce->cart->add_discount('layer2_discount');
} else {
$woocommerce->cart->remove_coupons('layer2_discount');
$woocommerce->cart->calculate_totals();
}
}
For some reason the second if statement only get detected, completely ignoring the first one. Is there anything noticeably wrong with the above?
Upvotes: 0
Views: 2088
Reputation: 11
Perhaps if you change the two separate statements into an if, elseif, else - it'll work.
add_action('woocommerce_before_cart', 'woobd_add_discount_if_enabled');
function woobd_add_discount_if_enabled()
{
global $woocommerce;
if ($woocommerce->cart->cart_contents_total >= 10
&& $woocommerce->cart->cart_contents_total <= 100
) {
$woocommerce->cart->add_discount('layer1_discount');
} elseif ($woocommerce->cart->cart_contents_total >= 100
&& $woocommerce->cart->cart_contents_total <= 200
) {
$woocommerce->cart->add_discount('layer2_discount');
} else {
$woocommerce->cart->remove_coupons('layer1_discount');
$woocommerce->cart->remove_coupons('layer2_discount');
$woocommerce->cart->calculate_totals();
}
}
Upvotes: 1