2

I have a requirement for the following: "For every time a user adds 3 of a particular product from a certain category they should get a defined free gift automatically added"

So if a customer adds 10 of this product then they should receive 3 X Free Gift

I've taken a look at the extensions out there but they don't really seem to be overly clear at what they are offering. My question is, does anyone know how to achieve the outcome either manually or via an extension?

Thanks in advance

2

Yes, you can achieve this by event observer.

Use the following event

checkout_cart_product_add_after

This event will call after the product was add to the cart. Refer this

Then use the following code in the observer to get the quote items

$quote= Mage::getSingleton('checkout/session')->getQuote(); 
foreach ($quote->getAllItems() as $item) { 
    $product = $item->getProduct(); // the product instance 
    /* you can add your condition here */
    var_dump($product->getName()); 
    var_dump($product->getCategoryIds()); 
    //to add your free gift product
    $freeProduct = Mage::getModel('catalog/product')->load(14);// use your free product id
    $quote->addProduct($freeProduct, array('qty' => '1', 'product_id' => $freeProduct->getId()));
    $quote->save();
}
  • Thank you for your guidance on this question, I have managed to develop the solution based on your advice! – CreativeNerdSam Jul 1 '15 at 15:19
1

I would observe the event sales_quote_collect_totals_after which is called everytime the cart has changed and after shopping cart rules are applied and totals recalculated.

It receives the quote as parameter, so that you can retrieve the items as follows:

$items = $observer->getQuote()->getAllVisibleItems();
$categoryQty = 0;
foreach ($items as $item) {
    if (CHECK_IF_ITEM_IS_IN_CATEGORY) {
        $categoryQty += $item->getQty();
    }
}
if ($categoryQty < 3) {
    return; //do nothing
}

(see also: How to get all items in cart currently?)

Then add the free gift like this

$product = Mage::getModel('catalog/product')->load(FREE_PRODUCT_ID);
$item = $observer->getQuote()->addProduct($product, floor($subTotal / 25));
$item->setCustomPrice(0);

It's important that you set the following flag to prevent the totals to be collected again after this change which would cause an infinite loop:

$observer->getQuote()->setTotalsCollectedFlag(true);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.