3

I'm building a shop based on WooCommerce. I need to add an extra checkbox on the checkout page called Shipping Insurance. Once the field is checked, i need to add an extra $3 to the Order Total. I was able to add a fixed fee this way:

function woo_add_cart_fee() {
  global $woocommerce;
  $woocommerce->cart->add_fee( __('Shipping Insurance', 'woocommerce'), 3 );

}
add_action( 'woocommerce_before_calculate_totals', 'woo_add_cart_fee' );

The problem is that this will add a fixed $3 to the order total, so its not optional. Any idea how to proceed with this issue?

2 Answers 2

5

Ok, so this is how i did it.

Create a product called Shipping Insurance which is $3, make sure its a hidden product(Catalog Visibility on the right side)

Use the following code in your theme's functions.php file:

add_action('woocommerce_cart_totals_after_shipping', 'wc_shipping_insurance_note_after_cart');
function wc_shipping_insurance_note_after_cart() {
global $woocommerce;
    $product_id = 669;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
    $_product = $values['data'];
    if ( $_product->id == $product_id )
        $found = true;
    }
    // if product not found, add it
if ( ! $found ):
?>
    <tr class="shipping">
        <th><?php _e( 'Shipping Insurance', 'woocommerce' ); ?></th>
        <td><a href="<?php echo do_shortcode('[add_to_cart_url id="669"]'); ?>"><?php _e( 'Add shipping insurance (+$3)' ); ?> </a></td>
    </tr>
<?php else: ?>
    <tr class="shipping">
        <th><?php _e( 'Shipping Insurance', 'woocommerce' ); ?></th>
        <td>$3</td>
    </tr>
<?php endif;
}

Change the $product_id variable to your product id that you created and when you're on checkout, it will simply add this hidden product to your cart

0

This won't completely answer your question, but the official WooCommerce documentation has an example similar to what you are hoping to achieve. In particular, you are looking for a combination of Lessons 1 and 2.

WooCommerce Documentation: Customizing checkout fields using actions and filters

Hopefully it fills in the time before someone can give a more specific answer.

Not the answer you're looking for? Browse other questions tagged or ask your own question.