Friday, November 21, 2014

Magento add products to cart programatically

Method 1:

$cart = Mage::getSingleton('checkout/cart');
$productIds = array(1,2,3,4);

foreach ($productIds as $productId) {
  $product = Mage::getModel('catalog/product');
  $product->load($productId);
  $cart->addProduct($product);
  $cart->save();
}

Method 2:

app/code/local/BTS/AddMultipleProducts/controllers/AddController.php;

<?php
class BTS_AddMultipleProducts_AddController extends Mage_Core_Controller_Front_Action {
 
    public function indexAction() {
        $products = explode(',', $this->getRequest()->getParam('products'));
        $cart = Mage::getModel('checkout/cart');
        $cart->init();
        /* @var $pModel Mage_Catalog_Model_Product */
        foreach ($products as $product_id) {
            if ($product_id == '') {
                continue;
            }
            $pModel = Mage::getModel('catalog/product')->load($product_id);
            if ($pModel->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_SIMPLE) {
                try {
                    $cart->addProduct($pModel, array('qty' => '1'));
                }
                catch (Exception $e) {
                    continue;
                }
            }
        }
        $cart->save();
        if ($this->getRequest()->isXmlHttpRequest()) {
            exit('1');
        }
        $this->_redirect('checkout/cart');
    }
 
}
?>

http://www.danneh.org/2011/09/adding-multiple-products-cart-simultaneously-magento-part-2/#ixzz3JkEd6JY6

No comments: