Angel Angel - 3 months ago 23
PHP Question

How to display Woocommerce product price by ID with correct Commas?

I was trying to display the price of a product on a custom page through a short code.

I found this thread: How to display Woocommerce product price by ID number on a custom page?

With this CODE:

function so_30165014_price_shortcode_callback( $atts ) {
$atts = shortcode_atts( array(
'id' => null,
), $atts, 'bartag' );

$html = '';

if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
$_product = wc_get_product( $atts['id'] );
$html = "price = " . $_product->get_price();
}
return $html;
}
add_shortcode( 'woocommerce_price', 'so_30165014_price_shortcode_callback' );


Shortcode:
[woocommerce_price id="99"]


I've implemented the code and got it working the only thing now is that the price is not being displayed right it's not registering the commas.

For example I have a price that's being displayed as
$13564.34


When it should be displayed as
$13,564.34


It's also doing the same for
$1371.43


When it should be displayed as
$1,371.43

Answer

The function number_format() may help. For example:

1578.47 would change to: 1,578.47 after

number_format(1578.47, 2, '.', ',');

http://php.net/manual/en/function.number-format.php

Comments