Search code examples
phpwordpresswoocommerceproduct

Display rounded product custom price with thousands separator using WooCommerce get_price


With woocommerce I am trying to get a custom rounded product price with thousands separator and currency:

Here is my code:

<?php 
    echo '$' . round((preg_replace('/[^0-9.]/', '', $product->get_price()) *1.04)); 
    // echo " - ";
    // echo number_format($product->get_price(), 0, '', '.') *1.04;
    ?> 

The commented php code is the code that I have used before and it didn't round the value...

Edit (Important):
This custom product price is the default price multiplied by 4% (x 1.04)


Solution

  • The WC_Product get_price() method output a float number and doesn't need preg_replace()

    The dedicated Woocommerce wc_price() formatting function, will add the necessary currency symbol and all needed separators as they are set in Woocommerce general settings

    So the final working code is:

    <?php echo wc_price( round($product->get_price() * 1.04) ); ?>
    

    Tested and works. It should solve everything.