I'm looking for the simplest way to implement something similar to Amazon's shopping cart icon which shows the number of items in the cart, which then links to the cart:

enter image description here

I've found several options through browsing various support requests etc, most of which are at least 3 years old and sound surprisingly complex in terms of overheads relying on many features (e.g. this suggestion from 2012 of creating an entire custom Views view to generate one number and one static link).

Obviously, the icon is the easy part, can be done in CSS very easily, it's the number of line items that I'm most interested in. Particularly having it integrated such that it updates when a new item is added to the cart.

I thought this would be something Commerce would do out of the box, or with an add-on module, but if it is I can't find it.

Is there any simple way?

  • Which version of Drupal are you using? Mar 18, 2016 at 23:31
  • 7 _____________ Mar 18, 2016 at 23:32
  • The reason I think it is not available out of the box is that it is a theming issue more so than anything else. I've seen it done on premium Drupal Commerce themes. Mar 21, 2016 at 6:54

1 Answer 1


The way I would do it, is that I would make the total number of products in the shopping cart available in the page.tpl.php file, and print it there directly.

Here's example code:

function YOUR_THEME_preprocess_page(&$variables) {
  $cart_count = 0;
  $order = commerce_cart_order_load($variables['user']->uid);
  if ($order) {
    $wrapper    = entity_metadata_wrapper('commerce_order', $order);
    $line_items = $wrapper->commerce_line_items;
    $cart_count = commerce_line_items_quantity($line_items, commerce_product_line_item_types());
  // Make the number of products in the shopping cart available to our template.
  $variables['products_in_shopping_cart'] = $cart_count;

Then in your page.tpl.php you would use this code to show the number of products in current user's cart:

<?php print $products_in_shopping_cart; ?>

Note: second argument passed to the commerce_line_items_quantity() is updated per Clive's note.

  • It's worth bearing in mind that not all line items are products, you can have discounts/shipping/etc too. This method might produce unexpected results without filtering on the line item type (which you can do with the 2nd arg to commerce_line_items_quantity)
    – Clive
    Mar 19, 2016 at 0:42
  • 3
    $cart_count = commerce_line_items_quantity($line_items, commerce_product_line_item_types()); should cover it
    – Clive
    Mar 19, 2016 at 0:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.