Skip to content

Instantly share code, notes, and snippets.

@MattRyanCo
Last active October 5, 2016 14:38
Show Gist options
  • Save MattRyanCo/735776b374ccdc2ab36b4b40b3b97b25 to your computer and use it in GitHub Desktop.
Save MattRyanCo/735776b374ccdc2ab36b4b40b3b97b25 to your computer and use it in GitHub Desktop.
Add variable USPS insurance fee to WooCommerce cart based on the value of the contents of the cart AND shipping with USPS
/**
* Add an insurance surcharge to your cart / checkout
* change the insurance amount based on value of cart
* Uses the WooCommerce fees API
*
*/
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping = $chosen_methods[0];
if ( strpos($chosen_shipping, 'usps') !== false ) {
// this compare needed since if the string is found at beg of target, it returns '0', which is a false value
$insurance_fee = 5;
if ( $woocommerce->cart->cart_contents_total <= 50 ) {
$insurance_fee = 0;
return;
} else {
if ( $woocommerce->cart->cart_contents_total > 100 ) {
$insurance_fee = 10;
}
}
$woocommerce->cart->add_fee( 'Insurance', $insurance_fee, true, '' );
}
return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment