How to display product price using shortcode

  • Home
  • How to display product price using shortcode

Here is the code snippet that you can use to create a shortcode and use it in any of your posts or pages to display the price of a specific product. You just have to specify the woocommerce product ID of that product like the given example. [woo_product_price id=20]

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function wptips_woo_price_shortcode( $atts ) {
$atts = shortcode_atts( array(
'id' => null,
), $atts, 'woocommerce_price' );
$html = '';
if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
$_product = wc_get_product( $atts['id'] );
$html = $_product->get_price();
}
return $html;
}
add_shortcode( 'woo_product_price', 'wptips_woo_price_shortcode' );
function wptips_woo_price_shortcode( $atts ) { $atts = shortcode_atts( array( 'id' => null, ), $atts, 'woocommerce_price' ); $html = ''; if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){ $_product = wc_get_product( $atts['id'] ); $html = $_product->get_price(); } return $html; } add_shortcode( 'woo_product_price', 'wptips_woo_price_shortcode' );
function wptips_woo_price_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'id' => null,
    ), $atts, 'woocommerce_price' );

    $html = '';

    if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
         $_product = wc_get_product( $atts['id'] );
         $html = $_product->get_price();
    }
    return $html;
}
add_shortcode( 'woo_product_price', 'wptips_woo_price_shortcode' );

2 Comments

  1. Alex

    I’m not sure if the latest update to WooCommerce broke your code. I get the following fatal error on my front end:

    Fatal error: Uncaught Error: Call to a member function get_price() on bool

    Reply
  2. Arnault

    Hi! How to display a price not just for 1 product but for any product?

    Reply

Leave a comment

0%