Simplest way to create a Commerce shopping cart icon showing the number of items 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:



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?
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(&amp;$variables) {
  $cart_count = 0;
  $order = commerce_cart_order_load($variables['user']-&gt;uid);
  if ($order) {
    $wrapper    = entity_metadata_wrapper('commerce_order', $order);
    $line_items = $wrapper-&gt;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:

&lt;?php print $products_in_shopping_cart; ?&gt;


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