When I need to know how many items the current user's cart have, I directly hit the db with a query to get the sum.
The query looks like

    $qty = intval(db_query('SELECT SUM(quantity) FROM commerce_line_item, field_data_commerce_line_items WHERE commerce_line_item.line_item_id = field_data_commerce_line_items.commerce_line_items_line_item_id
    AND commerce_line_item.type = \'product\' AND commerce_line_item.order_id = :order_id', array(':order_id' => $order->order_id))->fetchField());

The thing is, to keep all my modules independent, I sometime need to hit several time the database with the same query just to get this little bit of information ...

Would it be possible to have a helper function that caches (and update it when the cart is modified) the current quantity of product in an order ?
Something like : commerce_order_get_total_quantity($order)

Comments

rszrama’s picture

Status: Active » Fixed

There is a line item API function you can use, and using it won't require an additional query after the initial load. Just load the order, wrap it, and pass its line items array to commerce_line_items_quantity() like so:

$order = commerce_order_load(1);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$total_quantity = commerce_line_items_quantity($order_wrapper->commerce_line_items);

Note that you can do this multiple times in a page request and Drupal's entity cache for the order will be used. Additionally, you can pass a second parameter to that function to filter the line item types considered in your total count.

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.

ressa’s picture

Version: 7.x-1.x-dev » 7.x-1.2

If you want to get the total quantity of line items in the currently logged in user's cart, you can use the snippet below.

To test it, you can insert the snippet below in a Rule with Event: 'Calculating the sell price of a product', Actions: 'Execute custom PHP code' (without <?php ?> delimiters)

global $user;
$order = commerce_cart_order_load($user->uid);
$wrapper = entity_metadata_wrapper('commerce_order', $order);
$line_items = $wrapper->commerce_line_items;
$quantity = commerce_line_items_quantity($line_items, commerce_product_line_item_types());
print $quantity;