Reputation: 93
So I have a question I was hoping somebody might be able to help me out with...
I have a WordPress website that uses WooCommerce and I'm trying to do something relatively specific. The site has a fair deal of bulk pricing discounts for various products.
Now when it comes to the bulk pricing I kind of need the calculations to be done with four decimal places (i.e. $0.1234), So I have the WooCommerce settings set so that the number of decimals is 4.
The thing is, that on a lot of our products we don't have bulk pricing discounts; in most of these cases the four decimal places are completely unnecessary. (For example: $0.5500 or $12.0000) Is there any way I can trim the trailing the zeros but only if it is after the second decimal place?
For example, if I had $0.5500 it would be displayed as $0.55 and if I had $12.0000 it would be displayed as $12.00
I know a very similar question was asked a few years ago (see here), but unfortunately, the answer that worked in that case does not seem to work for me... That being said, I could be trying to use it the wrong way. I am not very familiar with using regular expressions in a WordPress "functions.php" file.
Any help at all would be greatly appreciated! Thanks!
Edit:
At this point I have something along the lines of:
add_action('wc_price', 'custom_price_disp');
function custom_price_disp($price) {
$count = null;
$resultingPrice = preg_replace('/(?<=\d{2})(0+)$/', '', $price, -1, $count);
return $resultingPrice;
}
But this code does not seem to work. Prices are still displayed the same as they were before.
Upvotes: 2
Views: 2069
Reputation: 51
You can use this function in your functions.php
child theme, it works fine and removes .00
from every price:
add_filter('woocommerce_price_trim_zeros', 'wc_hide_trailing_zeros', 10, 1);
function wc_hide_trailing_zeros( $trim ) {
// set to false to show trailing zeros
return true;
}
Upvotes: 4
Reputation: 2221
I’ve not used it myself, but based on the aforementioned wc_price()
method’s code, it looks like you can take advantage of a filter:
if ( apply_filters( 'woocommerce_price_trim_zeros', false ) && $decimals > 0 ) {
$price = wc_trim_zeros( $price );
}
You should be able to add this to your functions.php
:
add_filter( 'woocommerce_price_trim_zeros', true );
To trigger this behavior.
Upvotes: 1