如何使用正确的逗号按 ID 显示 Woocommerce 产品价格?
问题描述:
我试图通过短代码在自定义页面上显示产品的价格.
I was trying to display the price of a product on a custom page through a short code.
我找到了这个帖子:如何在自定义页面上按 ID 号显示 Woocommerce 产品价格?
使用此代码:
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"]
我已经实现了代码并让它工作,现在唯一的问题是价格没有正确显示,它没有注册逗号.
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.
例如,我的价格显示为 $13564.34
For example I have a price that's being displayed as $13564.34
什么时候应该显示为$13,564.34
它也对 $1371.43
什么时候应该显示为$1,371.43
答
现在开始工作.
代码:
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"]