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

By John Ennew | 16th April 2012

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"


Supriya Rajgopal's picture
Supriya Rajgopal
Supriya Rajgopal

This method is useful. However,if I wish to render $price_display in HTML tags, it prints junk values.
Ideally, we should use € but commerce_currency_format() returns '€'.
Kindly help.

Awaiting your response,

Supriya Rajgopal's picture
Supriya Rajgopal
Supriya Rajgopal

Hello, I found d solution myself. I used htmlentities() & rendered in HTML :)

Mike's picture

Very clear explanation. Very useful (especially for Drupal where clarity is not always its strong point). Many thanks

Alex's picture

Thank you, very useful tip. However it doesn't seems to output the price exactly like defined in the price field.

You do not have the necessary divs to make the ajax price refresh correctly and you do not have all special formatter related to product discounts.

So my question, how can you retrieve the product price exactly like if you used the price field display ?



John Ennew's picture
John Ennew
John Ennew

I think this is a question about what theme function to use and is very dependent on your application. This post is about rendering of the price itself and I am not sure how you would decide what theme function to use to get the result you want.

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.

Thanks a lot! You saved my time.

alex's picture

thank's, very useful

Add new comment