some one code:
<?php
class Yrcrz_AddFreeProduct_Model_Observer
{
public function sales_quote_save_before(Varien_Event_Observer $observer)
{
$quote = $observer->getQuote();
$freeProductId = 182;
$threshold = 100;
$freeProductExists = false;
$items = $quote->getAllItems();
foreach ($items as $item) {
if ($item->getProduct()->getId() == $freeProductId) {
$realGrandTotal = $quote->getGrandTotal() - $item->getRowTotalInclTax();
if ($realGrandTotal < $threshold) {
$quote->removeItem($item->getId());
return false;
}
$freeProductExists = true;
}
}
if ($freeProductExists || !$items) {
return false;
}
$cart = Mage::getSingleton('checkout/cart');
if ($quote->getGrandTotal() >= $threshold) {
$product = Mage::getModel('catalog/product')->load($freeProductId);
if ($product && $product->getId()) {
$params = array();
$cart->addProduct($product, $params);
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
}
}
}
}
This code checks to see if the threshold ($100) is reached, and if so it adds a product. It will also remove the free product if the grand total is under the threshold or there are no products. Note that you will need to define the ID of the free product with $freeProductId.
now, i want to extend the code, the $freeProductId i want to from a category, eg:$categoryId = 123;if i want to add other conditions, eg: if the threshold ($200) is reached, and if so it adds tow products. if the threshold ($500) is reached, and if so it adds three product. how do i do? i want a random product from a specified category? some one told me i need to just add a couple other if statements to do the check to the code- nothing too complicated.but after tried some time. i using the following code.i still don’t know how to write the code. thank you.
i do as i tried:
....$quote = $observer->getQuote();
$categoryId = 123;
$category = Mage::getModel('catalog/category')->load($categoryId); $prodCollection = $category->getProductCollection();
$prdIds=array();
foreach ($prodCollection as $product) {
$prdIds= $product->getId();
}
$freeProductId = array_rand($prdIds);;
$threshold = array(100,200,500);
$freeProductExists = false;
...
$cart = Mage::getSingleton('checkout/cart');
if ($quote->getGrandTotal() >= $threshold[0]) {
$product = Mage::getModel('catalog/product')->load($freeProductId);
if ($product && $product->getId()) {
$params = array();
$cart->addProduct($product, $params);
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
}
}elseif($quote->getGrandTotal() >= $threshold[1]){
}elseif($quote->getGrandTotal() >= $threshold[2]){
}
but i don’t know how to do want a random product from that category?how to add a couple other if statements to do the check