# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [WooCommerce](https://wpide.com/library/category/woocommerce/)
- Requires: WooCommerce
- Tags: woocommerce, checkout, fees, shipping
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/woo-shipping-insurance-option/

## Code

```php
$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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Optional Shipping Insurance at Checkout" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
