search

Home  >  Q&A  >  body text

Cart total for specific selected payment method in WooCommerce

If someone chooses cash on delivery, I need to round the final price at checkout

The general idea I want to achieve is:

if payment_method == 'cod'{
    $cart_subtotal = round($cart_subtotal);
}

P粉122932466P粉122932466250 days ago356

reply all(1)I'll reply

  • P粉554842091

    P粉5548420912024-03-22 21:21:25

    First, make sure the cart total is recalculated every time the user changes their payment method:

    add_action('wp_footer', 'trigger_checkout_refresh_on_payment_method_change');
    function trigger_checkout_refresh_on_payment_method_change(){
        if ( is_checkout() && ! is_wc_endpoint_url() ) :
        ?>
    
        sssccc
    
        
    

    Depending on the logic you want to implement, there are multiple ways to round the price, but if the user chooses "Cash on Delivery" as the payment method, here is the easiest way to round the total:

    add_filter( 'woocommerce_calculated_total', 'round_total_for_specific_payment_methods', 10, 2 );
    function round_total_for_specific_payment_methods( $total, $cart ) {
        $chosen_payment_method = WC()->session->get('chosen_payment_method');
        
        if ( $chosen_payment_method && $chosen_payment_method === 'cod' ) {
            $total = round( $total );
        }
        
        return $total;
    }
    

    reply
    0
  • Cancelreply