Search code examples
phpwordpresswoocommerceradio-buttoncart

Additional radio button in a custom checkout field group that update a fee in Woocommerce


This question is related "Update fee dynamically based on radio buttons in Woocommerce checkout" answer, which works nicely.

Actually there is 2 radio buttons in the field group and I would like to add an additional one (so 3 radio buttons at all).

My question is I would like to add an additional radio button, but I am just not seeing/understanding where to add an additional option.

I have added an extra field in the 'options' array: ...........................................................................

'options' => array(
            'bag' => __('In a bag '.wc_price(3.00), $domain),
            'box' => __('In a gift box '.wc_price(9.00), $domain),
            'speedboat' => __('In a speedboat '.wc_price(20.00), $domain),

...........................................................................

However I am confused by this section:

...........................................................................

$packing_fee = WC()->session->get( 'chosen_packing' ); // Dynamic packing fee
    $fee = $packing_fee == 'box' ? 9.00 : 3.00;
    $cart->add_fee( __( 'Packaging fee', 'woocommerce' ), $fee );

........................................................................

I tried adding:-

$packing_fee = WC()->session->get( 'chosen_packing' ); // Dynamic packing fee
    $fee = $packing_fee == 'box' ? 9.00 : 3.00 :;
    $cart->add_fee( __( 'Packaging fee', 'woocommerce' ), $fee );

but I doubt I am doing it right.

Can somebody please guide me on how to do this please?


Solution

  • For your 3 radio button (3 options in the array) like:

    'options' => array(
        'bag' => __('In a bag '.wc_price(3.00), $domain),
        'box' => __('In a gift box '.wc_price(9.00), $domain),
        'speedboat' => __('In a speedboat '.wc_price(20.00), $domain),
    ),
    

    You will have to replace this original code:

    $packing_fee = WC()->session->get( 'chosen_packing' ); // Dynamic packing fee
    $fee = $packing_fee == 'box' ? 9.00 : 3.00;
    $cart->add_fee( __( 'Packaging fee', 'woocommerce' ), $fee );
    

    with the following (for a third option):

    $packing_fee = WC()->session->get( 'chosen_packing' ); // Dynamic packing fee
    
    if( $packing_fee === 'box' )
       $fee = 9.00; 
    else if( $packing_fee === 'speedboat' ) 
       $fee = 20.00;
    else
       $fee = 3.00;
    
    $cart->add_fee( __( 'Packaging fee', 'woocommerce' ), $fee );
    

    or this similar in a more compact way:

    $packing_fee = WC()->session->get( 'chosen_packing' ); // Dynamic packing fee
    $fee = $packing_fee === 'bag' ? 3.00 : ( $packing_fee === 'box' ? 9.00 : 20.00 );
    $cart->add_fee( __( 'Packaging fee', 'woocommerce' ), $fee );
    

    Both should work.