1

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!

in2d
  • 544
  • 9
  • 19

1 Answers1

1

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,
);
David Wolf
  • 1,400
  • 1
  • 9
  • 18
  • Thanks for the effort and this seems like a good solution but unfortunately this site is not using PHP 8 – in2d Aug 05 '22 at 11:28
  • 1
    @in2d in this case you can just strip the named arguments, make sure to match the required order, `accepted_args` for example has to be on fourth place, etc (added it to the answer) – David Wolf Aug 05 '22 at 11:36
  • This line return an error [ 'decimals': 2 ], – in2d Aug 05 '22 at 11:45
  • 1
    Ah yea, my fault, we are not in JS, we are in PHP, therefore it has to be `=>` instead of `:` – David Wolf Aug 05 '22 at 11:46