WooCommerce Remove Extra Zero In 3 Decimal
I'm using 3 decimals so my price's seen as:
"$20.000" , "$20.050" , "$20.055"
I have search about removing zero decimals, and found this one:
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;
}
However, it is not working properly. Because It is only removing .000 decimals. ($20.000 to $20)
In addition, I want to just remove an extra 0 decimal from the last decimal segment.
For example;
"$20.000" to "$20.00"
"$20.050" to "$20.05"
"$20.055" will not change
Answer
Your above filter (which returns true
) triggers the execution of wc_trim_zeros()
function, which indeed removes zeros only if the price has only 0 decimals.
What you need is to use the formatted_woocommerce_price
hook instead.
The below filter will cut all trailing zeroes:
add_filter('formatted_woocommerce_price', function($formatted_price, $price, $decimals, $decimal_separator) {
// Need to trim 0s only if we have the decimal separator present.
if (strpos($formatted_price, $decimal_separator) !== false) {
$formatted_price = rtrim($formatted_price, '0');
// After trimming trailing 0s, it may happen that the decimal separator will remain there trailing... just get rid of it, if it's the case.
$formatted_price = rtrim($formatted_price, $decimal_separator);
}
return $formatted_price;
}, 10, 4);
UPDATE: the below code will only cut a trailing zero if it's the 3rd and last decimal:
add_filter('formatted_woocommerce_price', function($formatted_price, $price, $decimals, $decimal_separator) {
// Need to trim 0s only if we have the decimal separator present.
if (strpos($formatted_price, $decimal_separator) !== false) {
$formatted_price = preg_replace('/^(\d+' . preg_quote($decimal_separator, '/' ) . '\d{2})0$/', "$1", $formatted_price);
}
return $formatted_price;
}, 10, 4);
Disclaimer: code not tried out, written directly in the answer box.
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?