Sunday, July 5, 2009

How to show a distinct count of products in the cart

Overview
The standard Oscmax $cart->count_contents() function, which is used to display the number of items in a customer's shopping cart, has one major flaw: it incorporates counts of quantities in the total. First off, for stores that sell items priced by measurements - i.e. per inch, foot, yard etc. - using this will count the quantity of the unit rather than of products. For example, if a store sells wire by foot, and the customer places 5 feet of the same wire in the cart, the function will output "5 items in cart", whereas if the customer changes to 3 feet, it will output "3 items in cart". This is quite confusing - after all the customer didn't really alter the number of products in the cart... Plus, from a sales point of view, the number can escalate quickly, making the customer feel as if their cart is full and hurry to checkout (rather than spend more time browsing the catalog).

To resolve this, the following function will show the number of distinct products in a customer's cart - equivalent to the number of rows in the shopping cart page. Using the above example, it will show "1 item in cart" for the wire regardless of the quantity.

How to implement
1) Open the file catalog/includes/classes/shopping_cart.php

2) Find the following (without the quotes): "function count_contents()"

3) A few lines under find "return $total_items; }"

4) After that bracket ("}") Add the following:

//---

function count_contents_distinct() { // get number of different products in cart
$total_items = 0;
if (is_array($this->contents)) {
reset($this->contents);
while (list($products_id, ) = each($this->contents)) {
$total_items += $this->in_cart($products_id);
}
}
return $total_items;
}

//---

5) Then, wherever you want the count to appear (for example in shopping_cart.tpl.php) add the following code:



6) NOTES:
- It's better to create a new function than alter the existing count_contents one, since it's used in several other places for calculations etc.
- This does not group attributes, meaning that if the customer adds the same product with different attributes to the cart (i.e. wire --> blue and wire --> green) it will show as two different products. Basically if it shows as a new product in the shopping cart page, it will be counted separately here.

What's next?
You can take this a step further and count only specific items in the cart, then prevent the customer from checking out if a specific condition is not satisfied. More on that later...

P.S. This only works for Oscmax - however I plan to post the code for Oscommerce soon, so stay tuned!

No comments:

Post a Comment