Code to Enable Round Off Price
Add the following code to your theme’s functions.php file or inside a custom plugin:
// For round off functionality
add_action( ‘woocommerce_review_order_before_payment’, ‘cb_checkout_donation_choice’ );
function cb_checkout_donation_choice() {
$chosen = WC()->session->get( ‘donation_chosen’ );
$chosen = empty( $chosen ) ? WC()->checkout->get_value( ‘donation_choice’ ) : $chosen;
$chosen = empty( $chosen ) ? ‘0’ : $chosen;
$args = array(
‘type’ => ‘radio’,
‘class’ => array( ‘form-row-wide’, ‘update_totals_on_change’ ),
‘options’ => array(
‘1’ => ‘Yes. Round up my Total.’, // change text as needed
‘0’ => ‘No. Thank you.’, // change text as needed
),
‘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 Fee to cart and calculate amount to round up
add_action( ‘woocommerce_cart_calculate_fees’, ‘cb_checkout_donation_choice_fee’, 20, 1 );
function cb_checkout_donation_choice_fee( $cart ) {
if ( is_admin() && ! defined( ‘DOING_AJAX’ ) ) return;
$radio = WC()->session->get( ‘donation_chosen’ );
if ( $radio ) {
if ( ! WC()->cart->prices_include_tax ) {
$total = WC()->cart->cart_contents_total + WC()->cart->shipping_total;
}
$rounded_up_amount = ceil( $total );
$fee = $rounded_up_amount – $total;
if ( $fee == 0 ) {
$fee = 1;
}
if ( $fee > 0 ) {
$cart->add_fee( ‘Round Off’, $fee ); // change Donation label if needed
}
}
}
// Add Choice to 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’, $output[‘donation_choice’] );
}
}
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.
