Code to Enable Round Off Price
Add the following code to your theme’s functions.php file or inside a custom plugin:
[code_panel]
// Round Off option on checkout
add_action( ‘woocommerce_review_order_before_payment’, ‘cb_checkout_donation_choice’ );
function cb_checkout_donation_choice() {
$chosen = WC()->session->get( ‘donation_chosen’ );
if ( empty( $chosen ) ) {
$chosen = WC()->checkout->get_value( ‘donation_choice’ );
}
if ( empty( $chosen ) ) {
$chosen = ‘0’;
}
$args = array(
‘type’ => ‘radio’,
‘class’ => array( ‘form-row-wide’, ‘update_totals_on_change’ ),
‘options’ => array(
‘1’ => ‘Yes. Round up my Total.’,
‘0’ => ‘No. Thank you.’,
),
‘default’ => $chosen,
);
echo ‘<div class=”round-off-box”>’;
echo ‘<h3>Round off the product price.</h3>’;
woocommerce_form_field(
‘donation_choice’,
$args,
$chosen
);
echo ‘</div>’;
}
// Add Round Off fee to cart
add_action( ‘woocommerce_cart_calculate_fees’, ‘cb_checkout_donation_choice_fee’, 20, 1 );
function cb_checkout_donation_choice_fee( $cart ) {
// Don’t run in WooCommerce admin unless it’s an AJAX request
if ( is_admin() && ! defined( ‘DOING_AJAX’ ) ) {
return;
}
if ( ! WC()->session ) {
return;
}
$radio = WC()->session->get( ‘donation_chosen’ );
// Only add the fee when “Yes” is selected
if ( $radio !== ‘1’ ) {
return;
}
// Get current cart total
$total = $cart->get_cart_contents_total();
// Add shipping cost
$total += $cart->get_shipping_total();
// Round up to the next whole number
$rounded_up_amount = ceil( $total );
// Calculate round-off amount
$fee = $rounded_up_amount – $total;
// If already a whole number, add 1
if ( $fee <= 0 ) {
$fee = 1;
}
// Add Round Off fee
$cart->add_fee(
‘Round Off’,
$fee,
false
);
}
// Save Round Off choice to WooCommerce session
add_action(
‘woocommerce_checkout_update_order_review’,
‘cb_checkout_donation_choice_set_session’
);
function cb_checkout_donation_choice_set_session( $posted_data ) {
parse_str( $posted_data, $output );
if ( isset( $output[‘donation_choice’] ) ) {
WC()->session->set(
‘donation_chosen’,
sanitize_text_field( $output[‘donation_choice’] )
);
}
}
[/code_panel]
How This Works
-
Option at Checkout
A radio button is displayed asking the customer whether they want to round up their total. -
Calculation of Round Off Amount
If the customer selects “Yes,” WooCommerce calculates the difference between the current total and the next whole number.Example:
-
Order Total = ₹784.20
-
Rounded Total = ₹785.00
-
Extra Fee = ₹0.80
-
-
Add Fee Automatically
The calculated difference is added as a fee called Round Off (you can rename this label). -
Saved in Session
The customer’s choice is stored in session and applied dynamically.
Final Result
-
On the checkout page, customers will see an option:
Yes. Round up my total.
No. Thank you. -
If they choose Yes, the cart total will round up and display a new fee.
