获取购买产品的类别

I have this task to do, but I'm stuck on it. Client wants to get a category name product was purchased at. This info normally is not set. So at first step I'm trying to capture event checkout_cart_product_add_after and set a category for product.

So in my Observer.php I try to get current category, by:

Mage::registry('current_category')->getName()

but it appears that current_category object is not set in Mage registry. How can I add a category to a product in a different way? (Note that, product may belong to many categories, I just need the one at which it was purchased).

Regards, ventus

Keeping this data in user session is not so good idea. There is another way. On product page I add a hidden input tag with current category id, which can be received by $product->getCategory()->getEntityId().

Second step is more difficult. Before I have added new field (attribute) to the sales_flat_quote_item and sales_flat_order_item named from_category (my custom name ;)). Now I use observer for event sales_quote_save_before and I set to Quote Item my custom attribute.

To convert quote item to order item with my custom attribute I just added to config.xml global section:


<fieldsets>
  <sales_convert_quote_item>
    <from_category>
      <to_order_item>*</to_order_item>
    </from_category>
  </sales_convert_quote_item>
</fieldsets>

Now I can use it on checkout.

create your session object and store the Mage::registry('current_category')->getName(); there then:

  • you can get it even if the user has moved away to product page
  • you can decide what to do if this is empty and the client has accessed the product page directly

of-course you can tell your client that this is not a foolproof solution and instead of this he might just set up funnels for google analytics and have the correct statistics of client whereabouts on the page