Labs

By John Ennew | 16th April 2012

Drupal Commerce: Getting the price of a product as a nicely formatted string (programatically)

We are enjoying using the Drupal Commerce Framework. Here are a few programming tips.

Easy bit - How to load a commerce product with product_id of 10

$product = commerce_product_load(10);

If you have a commerce product - you can get its price information using entity api's excellent wrapper.

$price = entity_metadata_wrapper('commerce_product', $product)->commerce_price->value();

$price is an array containing the amount (in minor units e.g. 7600 for £76) and currency_code (e.g. 'GBP')

Finally, if you want to get the price as a nice string for output in something custom you can then use:

$price_display = commerce_currency_format($price['amount'], $price['currency_code'], $product);

Which will return "£76.00"

An even better function is this which will also take account of product pricing rules that might be in place:

$price = commerce_product_calculate_sell_price($product); 

Comments

No, it seems you were right, and my IDE debug tools were wrong !

I apology.

Just a point, there is a typo in one of the snippets, in the first declaration of $price.

The commerce_price method is a method of the $product object, so it must be :

$price = entity_metadata_wrapper('commerce_product', $product->commerce_price)->value();

But anyway, a HUGE thank to this very useful post.

turbopxl
turbopxl

Thanks a lot! You saved my time.

alex's picture
alex
alex

thank's, very useful

Add new comment