I need to get the number of items in cart of current anonymous customer on the site. I am using Drupal 7 and Drupal Commerce.

1 Answer 1


To load the current anonymous user cart, you can use commerce_cart_order_load something like this should suffice:

It gets the product count as separate line items and the product quantity including number of items per line item.

// Can leave blank or provide UID
$uid = 0; // anon
$product_count = 0;
$product_quantity_count = 0;

// Load cart order
if ($order = commerce_cart_order_load($uid)) {
  // Let's use the wrapper because it rocks
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);

  // Loop over line items and increment product counter
  foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
    // If line item is a commerce product type
    if (in_array($line_item_wrapper->type->value(), commerce_product_line_item_types())) {
      // Increment counters
      // Individual product line item
      // Number of items of product line item (quantity)
      $product_quantity_count += $line_item_wrapper->quantity->value();    

  // Debug output
  drupal_set_message(t('User %uid has %count products in cart with a total of %quantity items', 
    array('%uid' => $uid, '%count' => $product_count, '%quantity' => $product_quantity_count)));
  • Oh... Sorry, but when I simply log in and just after that log off I have an error: "EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. in EntityDrupalWrapper->set() (line 736 of (...)\sites\all\modules\entity\includes\entity.wrapper.inc)." How can I fix it? Sep 29, 2014 at 23:53
  • The above code doesn't use ->set() perhaps you have a misconfigured rule? Sep 30, 2014 at 2:55
  • @ihateubercart I've also adjusted the code to ensure the order is returned prior to creating the wrapper, perhaps that will help. Sep 30, 2014 at 2:57

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.