如何使用正确的逗号按 ID 显示 Woocommerce 产品价格?

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

我试图通过一个短代码在自定义页面上显示产品的价格。

我找到了这个帖子:

使用此代码:

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' );

短代码: [woocommerce_price id="99"]

我已经实现了代码并使其正常工作,现在唯一的问题是价格显示不正确,它没有注册逗号。

例如,我有一个显示为 564.34

的价格

什么时候应该显示为,564.34

它也在为 71.43

做同样的事情

什么时候应该显示为,371.43

函数 number_format() 可能会有所帮助。例如:

1578.47 将更改为:

后 1,578.47
number_format(1578.47, 2, '.', ',');

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

现在可以使用了。

代码:

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'] );
 $number = number_format($_product->get_price(), 2, '.', ',');
 $html = "$" . $number;

 }
 return $html;
 }
 add_shortcode( 'woocommerce_price', 'so_30165014_price_shortcode_callback' );

短代码:

[woocommerce_price id="99"]