Search code examples
phpwordpresswoocommerceproduct

Custom variable product formatted price without decimals in Woocommerce


I am currently using this additional code in my functions.php in the activated child-theme to remove the price ranges when the product is using variations (so it would show just the price "From: X$" not "From: X$ - Y$"):

add_filter( 'woocommerce_variable_sale_price_html',
'lw_variable_product_price', 10, 2 );
add_filter( 'woocommerce_variable_price_html',
'lw_variable_product_price', 10, 2 );

function lw_variable_product_price( $v_price, $v_product ) {

// Regular Price
$v_prices = array( $v_product->get_variation_price( 'min', true ),
                            $v_product->get_variation_price( 'max', true ) );
$v_price = $v_prices[0]!==$v_prices[1] ? sprintf(__('From: %1$s', 'woocommerce'),
                       wc_price( $v_prices[0] ) ) : wc_price( $v_prices[0] );

// Sale Price
$v_prices = array( $v_product->get_variation_regular_price( 'min', true ),
                          $v_product->get_variation_regular_price( 'max', true ) );
sort( $v_prices );
$v_saleprice = $v_prices[0]!==$v_prices[1] ? sprintf(__('From: %1$s','woocommerce')
                      , wc_price( $v_prices[0] ) ) : wc_price( $v_prices[0] );

if ( $v_price !== $v_saleprice ) {
$v_price = '<del>'.$v_saleprice.$v_product->get_price_suffix() . '</del> <ins>' .
                       $v_price . $v_product->get_price_suffix() . '</ins>';
}
return $v_price;
}

The only problem here is already mentioned in the title. I need to show price in the product list (default shop page) without decimals, not like it's currently showing: enter image description here

I am sure that without this additional code I am using it's without these zeros.

It looks much better without the two zeros at the end, believe me.


Solution

  • To show the price without decimals you need to use 'decimals' argument in the Woocommerce wc_price() formatting function…

    So for example with a price of 499.00, you will add to wc_price() the argument array('decimals' => 0):

    echo wc_price( 499.00, array('decimals' => 0) );
    

    It will output the formatted html price without decimals.

    As you can see it removes the decimals from any formatted price using wc_price() function, so in your code for example:

    $v_price = $v_prices[0]!==$v_prices[1] ? sprintf(__('From: %1$s', 'woocommerce'),
    wc_price( $v_prices[0], array('decimals' => 0) ) ) : wc_price( $v_prices[0], array('decimals' => 0) );
    

    For variable product custom prices, just as you want see the following answer:

    WooCommerce variable products: keep only "min" price with a custom label

    You will have just to add array('decimals' => 0) to wc_price() function