Custom Price Option WooCommerce
May 27, 2025 · AI Conversations
User
update woocommerce cart toal and set custom price when check radion button at checkout page
Assistant
To **update the WooCommerce cart total and set a custom price** when a radio button is selected on the **checkout page**, follow these steps:
—
### ✅ Step 1: Add the Radio Buttons on Checkout Page
Add this to your theme’s `functions.php` or in a custom plugin:
add_action('woocommerce_review_order_before_payment', 'add_custom_price_option_radio');
function add_custom_price_option_radio() {
?>
<div id="custom-price-options">
<h3>Choose Your Option</h3>
<p><label><input type="radio" name="custom_price_option" value="0" checked> Default</label></p>
<p><label><input type="radio" name="custom_price_option" value="50"> Add ₹50 Extra</label></p>
<p><label><input type="radio" name="custom_price_option" value="100"> Add ₹100 Extra</label></p>
</div>
<?php
}
—
### ✅ Step 2: Save the Selected Option via AJAX
Add this JavaScript using `wp_footer` hook or enqueue it:
add_action('wp_footer', 'custom_price_option_script');
function custom_price_option_script() {
if (is_checkout()) :
?>
<script>
jQuery(function($){
$('form.checkout').on('change', 'input[name=custom_price_option]', function(){
var selected = $('input[name=custom_price_option]:checked').val();
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: {
action: 'set_custom_price_option',
value: selected
},
success: function() {
$('body').trigger('update_checkout');
}
});
});
});
</script>
<?php
endif;
}
—
### ✅ Step 3: Handle the AJAX & Store in Session
add_action('wp_ajax_set_custom_price_option', 'set_custom_price_option');
add_action('wp_ajax_nopriv_set_custom_price_option', 'set_custom_price_option');
function set_custom_price_option() {
if (isset($_POST['value'])) {
WC()->session->set('custom_price_addition', floatval($_POST['value']));
}
wp_die();
}
—
### ✅ Step 4: Modify Cart Total Based on Selection
add_action('woocommerce_cart_calculate_fees', 'apply_custom_price_fee', 20, 1);
function apply_custom_price_fee($cart) {
if (is_admin() && !defined('DOING_AJAX')) return;
$fee = WC()->session->get('custom_price_addition');
if ($fee > 0) {
$cart->add_fee('Custom Option Fee', $fee);
}
}
—
### ✅ Optional: Show the Choice on Order Meta (Backend)
add_action('woocommerce_checkout_create_order', 'save_custom_price_option_to_order', 20, 2);
function save_custom_price_option_to_order($order, $data) {
$fee = WC()->session->get('custom_price_addition');
if ($fee) {
$order->add_meta_data('_custom_price_option_fee', $fee);
}
}
—
### 💡 Result:
– User picks a radio option at checkout.
– Fee is dynamically applied and cart total is updated.
– The selection is stored in the order for reference.
Let me know if you want this to **replace the total price** instead of adding to it.