How to display Woocommerce product price by ID wit

2019-07-26 23:10发布

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

2条回答
可以哭但决不认输i
2楼-- · 2019-07-26 23:19

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

查看更多
啃猪蹄的小仙女
3楼-- · 2019-07-26 23:33

GOT IT WORKING NOW.

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

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

SHORTCODE:

[woocommerce_price id="99"]
查看更多
登录 后发表回答