Skip to content

Instantly share code, notes, and snippets.

@isaumya
Created April 29, 2020 05:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isaumya/acacf5961d55aa5f0cd454622ea5f542 to your computer and use it in GitHub Desktop.
Save isaumya/acacf5961d55aa5f0cd454622ea5f542 to your computer and use it in GitHub Desktop.
A function to get the simple product or variation product's price by passing the product_is or variation_id in WooCommerce.

When to use it?

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.

The Function

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';
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment