WordPress / Web Development Tutorials
(Best WordPress Tutorials)

CSSHTMLJavaScriptjQueryMySQLPHPSilvaTechnologiesWooCommerceWordpress
Silva Web Designs - Blog

How to Add the Product Price in WooCommerce as a Shortcode

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().'"]');

 

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well as many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

One thought on “How to Add the Product Price in WooCommerce as a Shortcode

Join the discussion