问题
I'd like to know if there is a way to round up the prices in WooCommerce keeping 2 decimals displayed (so the price will end with the first and second decimal ,00).
For example: €12,54 will be rounded to €13,00 and €145,67 will be rounded up to €146,00.
I'm using a plugin to discount the product price i.e. €39,00 - 20% = €35,10 (it should became €36,00).
I'd like to round up all the prices as explained before.
Is there a way to do so?
回答1:
You can't really round up globally all real calculated prices, like taxes, shipping, discounts, totals and others third party plugins calculated prices. Rounding calculated prices requires to be done case by case…
You can only round up globally all "displayed" formatted prices keeping the 2 decimals. For that there are 2 steps explained below:
1) The following hooked function will round the raw displayed prices in WooCommerce:
It will return the next highest integer value by rounding up that value if necessary.
add_filter( 'raw_woocommerce_price', 'round_up_raw_woocommerce_price' )
function round_up_raw_woocommerce_price( $price ){
return ceil( $price );
}
Code goes in functions.php file of your active child theme (or active theme).
Note that All Woocommerce price formatting functions will use our rounded prices from our first hooked function…
2) Formatting displayed prices in WooCommerce.
WooCommerce uses the function wc_price() everywhere to format prices as defined in the WooCommerce settings.
So if you need to format any raw price you will use that formatting function like in this example:
// Get the WC_Product Object instance from the product ID
$product = wc_get_product ( $product_id );
// Get the product active price for display
$price_to_display = wc_get_price_to_display( $product );
// Format the product active price
$price_html = wc_price( $price_to_display );
// Output
echo $price_html
Or the same thing, more compact using WC_Product
built in method get_price_html()
:
// Get the WC_Product Object instance from the product ID
$product = wc_get_product ( $product_id );
// Display the formatted product price
echo $product->get_price_html();
来源:https://stackoverflow.com/questions/61836970/how-can-i-round-up-the-price-in-woocommerce