Home > Back-end >  Add 3 decimal places to everywhere except minicart, cart and checkout Woocommerce
Add 3 decimal places to everywhere except minicart, cart and checkout Woocommerce

Time:08-06

I have come across issue where I want to show 3 decimal places everywhere on the site except cart, checkout and minicart. For that I have added this code to my functions.php file.

add_filter( 'wc_get_price_decimals' , 'custom_price_decimals', 20, 1 );
function custom_price_decimals( $decimals ) {
    if( is_checkout() || is_page( 'cart' ) || is_cart() ) {
        $decimals = 2;
    } else{
        $decimals = 3;
    }
    return $decimals;
}

It shows the results on cart and checkout with 2 decimal places and the rest of the site 3 decimal places. The issue here is that because mini-cart.php isn't on separate page it will show prices with 3 decimals places instead of 2. Can anyone suggest me a workaround because I am not seeing one. Cheers!

CodePudding user response:

When you have a look into cart/mini-cart.php of the WC templates, you will find this line:

apply_filters( 'woocommerce_cart_item_price', WC()->cart->get_product_price( $_product ), $cart_item, $cart_item_key );

So, if you want to make sure you only have 2 decimals inside the minicart, where this filter is applied, you can add a custom filter and apply your logic to only keep 2 decimals, for example using the wc price formatting function wc_price:

add_filter(
    hook_name: 'woocommerce_cart_item_price',
    accepted_args: 3,
    callback: function (string $price, array $item, string $key): string {
        return wc_price(
            price: $item['data']->get_price(),
            args: [ 'decimals' => 2 ],
        );
    },
);
  • Note, I did not test the snippet.
  • Also note that named function arguments require at least PHP 8

Lower than PHP 8:

add_filter(
    'woocommerce_cart_item_price',
    function (string $price, array $item, string $key): string {
        return wc_price(
            $item['data']->get_price(),
            [ 'decimals' => 2 ],
        );
    },
    10,
    3,
);
  • Related