Lets say in your template you are doing something like a pricing table, where instead of manually putting the price, you just want to pass the variation_id
or the product_id
(in case of simple product and dynamically get the price of the product.
This is helpful in many cases:
- You don't have to manage price in two places & if you update the price of the product it will be reflected everywhere.
- If you are using country based pricing and want to show the price accordingly.
Here is the function which comes to rescue.
/**
* Get the price of WooCommerce Normal or Variable Product by passing product_id/variation_id
*
* @param number $prod_id The product_is/variation_id
* @param boolean $return_html If the function should return the price in HTML or just the price without currency sign
* @return string $price The product price
*/
function get_woo_prod_price( $prod_id, $return_html ) {
if( function_exists( 'wc_get_product' ) ) {
$product = wc_get_product($prod_id);
if($return_html) {
$price = $product->get_price_html();
} else {
$price = $product->get_price();
}
return $price;
} else {
return 'Install/Activate WooCommerce';
}
}