Round cart subtotal in WooCommerce

Viewed 814

While using this code I can manipulate the subtotal (It works correct)

add_action( 'woocommerce_calculate_totals', 'action_cart_calculate_totals', 10, 1 );
function action_cart_calculate_totals( $cart_object ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( !WC()->cart->is_empty() ):
        ## Displayed subtotal (+10%)
        $cart_object->subtotal *= 1.1;

        ## Displayed TOTAL (+10%)
        // $cart_object->total *= 1.1;

        ## Displayed TOTAL CART CONTENT (+10%)
        // $cart_object->cart_contents_total *= 1.1;

    endif;
}

But I would like to use the code below, for the new subtotal

add_filter( 'woocommerce_calculated_total', 'my_custom_roundoff' );
function my_custom_roundoff( $total ) {
    $round_num = round($total / 0.05) * 0.05;
    $total = number_format($round_num, 2); // this is required for showing zero in the last decimal
    return $total;
}

However this does not have the desired result. How can I use this rounding function in the first mentioned function?

1 Answers

woocommerce_calculated_total hook is used to allow plugins to filter the grand total, and sum the cart totals in case of modifications.

For the subtotal, use the woocommerce_cart_subtotal filter hook instead.

So you get:

function filter_woocommerce_cart_subtotal( $subtotal, $compound, $cart ) {
    // Rounds a float
    $round_num = round( $cart->subtotal / 0.05 ) * 0.05;
    
    // Format a number with grouped thousands
    $number_format = number_format( $round_num, 2 );
    
    // Subtotal
    $subtotal = wc_price( $number_format );

    return $subtotal;
}
add_filter( 'woocommerce_cart_subtotal', 'filter_woocommerce_cart_subtotal', 10, 3 );
Related