php – Automatically change insurance quantity based on cart total


I just added an insurance-button to my cart page where a hidden insurance product is automatically added to the cart if the clients wishes so. Therefore I used and upated an older PHP snippet I found that was recommended by woocommerce for cases like this. This works quite fine.

My problem is that this function should not add only one insurance – it should automatically add a quantity of insurances based on the total number of products in the cart. For example: When the customer buys a total quantity of five products and wants to get an insurance it should add the insurance five times when he clicks the button.

I know I can get the number of cart items including their quantity counts with WC()->cart->get_cart_contents_count() but I can’t figure out how to use this in my PHP snippet or the shortcode. Maybe someone can help?

Here’s my originally code:

add_action('woocommerce_cart_totals_after_shipping', 'wc_shipping_insurance_note_after_cart');
function wc_shipping_insurance_note_after_cart() {
global $woocommerce;
    $product_id = 7597;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
    $_product = $values['data'];
    if ( $_product->id == $product_id )
        $found = true;

if ( ! $found ):
    <tr class="woocommerce-shipping-totals shipping">
        <th><?php _e( 'Versicherung', 'woocommerce' ); ?></th>
        <td data-title="Versicherung"> <p>Rücknahmeschutz: Erstattung der Kosten z.B. bei Erkrankung. Infos <a href="">hier</a>. 
            </p><a href="<?php echo do_shortcode('[add_to_cart_url id="7597"]'); ?>"><button><?php _e( 'Hinzufügen (+17,90€/Ticket)' ); ?> </button></a></td>
<?php else: ?>
    <tr class="woocommerce-shipping-totals shipping">
        <th><?php _e( 'Versicherung', 'woocommerce' ); ?></th>
        <td data-title="Versicherung">€17,90</td>
<?php endif;

Stephan Rathgeber 1 month 2022-12-22T03:22:53-05:00 0 Answers 0 views 0

Leave an answer