Skip to content

Instantly share code, notes, and snippets.

@Zach-Toth
Last active July 30, 2020 00:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zach-Toth/95041d32b072109fa8fd99c60eff1c5a to your computer and use it in GitHub Desktop.
Save Zach-Toth/95041d32b072109fa8fd99c60eff1c5a to your computer and use it in GitHub Desktop.
Charge shipping insurance based on cart total with Woocommerce and USPS Simple Woo Plugin
/**
* Add a shipping insurance surcharge to your cart / checkout
* change the insurance amount based on value of cart
* Uses the WooCommerce fees API
* Written for use with USPS Simple Woo Shipping plugin - Change $chosen_methods to your shipping methods
* Uses USPS shipping rates
* Based on Gist by MattRy
*
*/
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
//General Fall back for shipping and cart totals <= 50
$insurance_fee = 0;
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping = $chosen_methods[0]; {
if ( $chosen_shipping == 'local_pickup:3' ) {
$insurance_fee = 0;
} else if ( $woocommerce->cart->cart_contents_total > 500 ) {
$insurance_fee = 7.30;
} else if ( $woocommerce->cart->cart_contents_total > 400 ) {
$insurance_fee = 6.40;
} else if ( $woocommerce->cart->cart_contents_total > 300 ) {
$insurance_fee = 5.50;
} else if ( $woocommerce->cart->cart_contents_total > 200 ) {
$insurance_fee = 4.60;
} else if ( $woocommerce->cart->cart_contents_total > 100 ) {
$insurance_fee = 2.45;
} else if ( $woocommerce->cart->cart_contents_total >= 50 ) {
$insurance_fee = 2.05;
}
}
//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, '' );
}
@lka674
Copy link

lka674 commented Jul 30, 2020

Thank you so much for this code, but is there a way to have the calculation calculate the entire cart total...so the cart contents total PLUS whatever shipping/taxes the customer may have paid too...as those are coverable expenses for shipping insurance with my 3rd party carrier.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment