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')

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);

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"


John Ennew

I'm a Chartered Engineer and the Development Chapter Lead at Deeson. As an enthusiastic advocate of professional development I organise events and activities for the Kent network of the Institution of Engineering and Technology and run a Code Club. I'm also an Acquia Certified Drupal Grand Master and the UK Digital Agencies 2015 Techie of the Year.


Have a chat with us

New business:
+44 (0)1227469060

Client services:
+44 (0)1227469060

By submitting this form, you accept the Mollom privacy policy.