If you are looking to add the WooCommerce product price into your page layout, then you’re in the right place. You can add this as a shortcode using the product ID as an attribute for the correct product.
To do this, we need to add some code into our functions.php
file. Once we have done this, we can add the shortcode anywhere you would like to display the price.
So lets begin, first we add the below code to our functions.php
file:
/**
* Shortcode WooCommerce Product Price.
*/
add_shortcode( 'silva_product_price', 'silva_woo_product_price_shortcode' );
function silva_woo_product_price_shortcode( $atts ) {
$atts = shortcode_atts( array(
'id' => null
), $atts, 'silva_product_price' );
if ( empty( $atts[ 'id' ] ) ) {
return '';
}
$product = wc_get_product( $atts['id'] );
if ( ! $product ) {
return '';
}
return $product->get_price_html();
}
Once we have added this, we can then use the shortcode in the layout or template with the product ID number as an attribute as shown below:
# Add inside WYSIWYG editor
[silva_product_price id="<insert_product_id>"] // Replace this with the product ID
# Add within a page template, this has to be performed within the loop to get the unique product ID
echo do_shortcode('[silva_product_price id="'.get_the_ID().'"]');
Thank you, it works perfectly !
Thank you for guidance. But I want to get the price of the product to include in the article. When I change the price in the product, the price in the article also changes. So do it like this?