I am trying to create a custom checkout radio button that calculates restaurant tip in percentage.
For the radio button, the static value is working fine.
However, I want to get the subtotal and calculate certain percentage on custom radio button click.
This is my code
add_action( 'woocommerce_after_checkout_billing_form', 'add_box_option_to_checkout' );
function add_box_option_to_checkout( $checkout ) {
$chosen = WC()->session->get( 'tip' );
$chosen = empty( $chosen ) ? WC()->checkout->get_value( 'tip' ) : $chosen;
$chosen = empty( $chosen ) ? '0' : $chosen;
$total = WC()->cart->get_subtotal();
$fivetip = $total * 0.05;
woocommerce_form_field( 'tip', array(
'type' => 'radio',
'class' => array( 'form-row-wide', 'update_totals_on_change' ),
'options' => array(
$fivetip => '5%',
'10.00' => '10%',
'15.00' => '15%',
),
), $chosen );
woocommerce_form_field( 'add_tip', array(
'type' => 'text',
'class' => array('add_tipform-row-wide'),
'placeholder' => __('Enter Custom Tip Amount')
), $checkout->get_value( 'add_tip' ));
}
add_action( 'woocommerce_cart_calculate_fees', 'checkout_tip_fee', 20, 1 );
function checkout_tip_fee( $cart ) {
if ( $radio = WC()->session->get( 'tip' ) ) {
$cart->add_fee( 'Tip', $radio );
}
}
add_action( 'woocommerce_checkout_update_order_review', 'checkout_tip_choice_to_session' );
function checkout_tip_choice_to_session( $posted_data ) {
parse_str( $posted_data, $output );
if ( isset( $output['tip'] ) ){
WC()->session->set( 'tip', $output['tip'] );
}
}
2
Answers
You can get it like this:
So:
Now a jQuery script will empty the text field when a radio button is selected and vice versa:
Finally it calculates the amount of the fee based on the selected value calculated on the subtotal (excluding taxes) of the cart.
The code has been tested and works. Add it to your active theme’s functions.php.
The following is something advanced using Ajax and WC Sessions:
It will add a custom a tip (as a custom fee) based on selected radio buttons options: fixed percentages options or custom option that will show a text field to allow customer to input a fixed amount.
Displayed Fields are hand coded to get a better display than WooCommerce form fields for radio buttons (see the screenshots below).
How it works for the customer:
On checkout page load, a Tip of 5% (a fee) is applied (selected by default). When changing the selected option to something else, the applied fee changes.
If the "custom" option is selected, the fee is removed while a text field appears below:
Customer can input a fixed amount and a Tip (a fee) is applied with this amount.
Here is the code:
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Addition related to your comment:
To use cart items total
including
taxes replace in last function:with