2

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?

7uc1f3r
  • 28,449
  • 17
  • 32
  • 50
CJabber201
  • 97
  • 8

1 Answers1

2

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 );
7uc1f3r
  • 28,449
  • 17
  • 32
  • 50
  • High, it works fine! Thanks! Is it possible to get the price suffix behind it? – CJabber201 Jun 03 '21 at 10:34
  • @CJabber201 For the current output [wc_price()](https://github.com/woocommerce/woocommerce/blob/b19500728b4b292562afb65eb3a0c0f50d5859de/includes/wc-formatting-functions.php#L561) is used. To get the price suffix behind it: replace `$subtotal = wc_price( $number_format );` with `$subtotal = $number_format . get_woocommerce_currency_symbol();` – 7uc1f3r Jun 03 '21 at 10:42