Optional Shipping Insurance at Checkout
Offers a "Protect my parcel" checkbox on the classic checkout that adds an insurance fee based on the order value, and updates the totals instantly.
Opens WPIDE on
Code
$wpide_insurance = array(
'label' => 'Shipping insurance',
'percent' => 2, // Percent of the products subtotal.
'minimum' => 1.50, // Lowest fee charged.
);
$wpide_insurance_chosen = function () {
// phpcs:disable WordPress.Security.NonceVerification -- WooCommerce verifies its checkout requests.
if ( isset( $_POST['post_data'] ) ) {
parse_str( wp_unslash( $_POST['post_data'] ), $posted );
WC()->session->set( 'wpide_insurance', ! empty( $posted['wpide_insurance'] ) );
} elseif ( isset( $_POST['woocommerce-process-checkout-nonce'] ) ) {
WC()->session->set( 'wpide_insurance', ! empty( $_POST['wpide_insurance'] ) );
}
// phpcs:enable
return (bool) WC()->session->get( 'wpide_insurance', false );
};
add_action( 'woocommerce_review_order_before_order_total', function () use ( $wpide_insurance, $wpide_insurance_chosen ) {
if ( ! WC()->cart->needs_shipping() ) {
return;
}
printf(
'<tr class="wpide-insurance"><th>%s</th><td><label><input type="checkbox" name="wpide_insurance" value="1" class="update_totals_on_change" onchange="jQuery(document.body).trigger(\'update_checkout\')" %s> %s</label></td></tr>',
esc_html( $wpide_insurance['label'] ),
checked( $wpide_insurance_chosen(), true, false ),
esc_html( 'Protect my parcel against loss and damage' )
);
} );
add_action( 'woocommerce_cart_calculate_fees', function ( $cart ) use ( $wpide_insurance, $wpide_insurance_chosen ) {
if ( ( is_admin() && ! wp_doing_ajax() ) || ! WC()->session || ! $cart->needs_shipping() || ! $wpide_insurance_chosen() ) {
return;
}
$fee = max( $wpide_insurance['minimum'], $cart->get_subtotal() * $wpide_insurance['percent'] / 100 );
$cart->add_fee( $wpide_insurance['label'], round( $fee, wc_get_price_decimals() ), true );
} );
Notes
The fee is a percentage of the subtotal with a minimum, and customers can untick it any time before paying.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.