How to add a radio button with price on product page

How to add a radio button with price on product page? WordPress woocommerce

Add to follows code snippets to achieve your work:

function add_custom_fees_before_add_to_cart() {
    global $product;

    $args = array(
        'type' => 'radio',
        'class' => array( 'form-row-wide' ),
        'options' => array(
            '' => 'No Option',
            '10' => 'Option 1 ($10)',
            '30' => 'Option 2 ($30)',
        ),
        'default' => ''
    );
    ?>
    <div class="custom-fees-wrap">
        <label for="iconic-engraving"><?php _e( 'Customize Your Order!', 'textdomain' ); ?></label>
        <?php woocommerce_form_field( 'custom_fees', $args, '' ); ?>
    </div>
    <?php
}

add_action( 'woocommerce_before_add_to_cart_button', 'add_custom_fees_before_add_to_cart', 99 );


function save_value_add_cart_item_data( $cart_item_data, $product_id, $variation_id ) {
    $custom_fees = filter_input( INPUT_POST, 'custom_fees' );

    if ( empty( $custom_fees ) ) {
        return $cart_item_data;
    }

    $cart_item_data['custom_fees'] = $custom_fees;

    return $cart_item_data;
}

add_filter( 'woocommerce_add_cart_item_data', 'save_value_add_cart_item_data', 99, 3 );

function calculate_add_cart_fee() {
    global $woocommerce;
    $cart_items = $woocommerce->cart->get_cart();
    foreach( $cart_items as $key => $item ) { 
        if( !isset( $item['custom_fees'] ) && empty( $item['custom_fees'] ) ) continue;
        $woocommerce->cart->add_fee( __('Custom fees', 'textdomain'), $item['custom_fees'] );
    }
}
add_action( 'woocommerce_cart_calculate_fees', 'calculate_add_cart_fee', 99 );

Leave a Comment