Trying to add shipping insurance based on cart total in woocommerce with a multiple else if function. It seems only the first else if statement is working even when cart total is over $100. What am I missing?
$insurance_fee = 0;
$chosen_methods = WC()->session->get( 'USPS_Simple' );
$chosen_shipping = $chosen_methods[0]; {
if ( $woocommerce->cart->cart_contents_total >= 50 ) {
$insurance_fee = 2.05;
} else if ( $woocommerce->cart->cart_contents_total >= 100 ) {
$insurance_fee = 2.45;
} else if ( $woocommerce->cart->cart_contents_total >= 200 ) {
$insurance_fee = 4.60;
} else if ( $woocommerce->cart->cart_contents_total >= 300 ) {
$insurance_fee = 5.50;
} else if ( $woocommerce->cart->cart_contents_total >= 400 ) {
$insurance_fee = 6.40;
} else if ( $woocommerce->cart->cart_contents_total >= 500 ) {
$insurance_fee = 7.30;
}
}
//The fallback $insurance_fee value of 0 will be used if none of the conditions are met
$woocommerce->cart->add_fee( 'Shipping Insurance', $insurance_fee, true, '' );
Shipping insurance should return $2.45 since cart total is > $100
The first conditional block satisfies the criteria (if cart total is > $100, it's also > $50). Since the second block is an "else if", it will not be entered if the first condition is met. Try reversing the order of the conditions.
you have to add a <= for the statements. Like this:
if ( $woocommerce->cart->cart_contents_total >= 50 && $woocommerce->cart->cart_contents_total < 100 ) {
$insurance_fee = 2.05;
}
It is the default behavior of if else if
. When meets a condition, next conditions will never be evaluated as TRUE.
If you want to meet more than one conditions you can use if
instead of if else if
.