Breakfast in Capetown

Programatically add multiple products to a cart

After a few days of hunting for a solution, I finally bumped into this snippet and boy did I feel dumb. Anyway, I hope someone will find this useful.

1
2
3
4
5
6
7
8
9
10
try{
$cart = new Mage_Checkout_Model_Cart();
$cart->truncate();//clear existing cart items
$cart->init();
$cart->addProductsByIds($productIds);
$cart->save();
}
catch(Exception $e){
echo $e->getMessage();
}

Of course the above snippet will not work in isolation.  Below is an example of how I used it. I have put this snippet into a controller that then redirects to the users’ shopping cart. e.g. http://myshop/mycheckout/addmultipletocart/?product_id[]=1&product_id[]=24&product_id[]=987&customer_id=32

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$params = $this->getRequest()->getParams();
$redirect = "checkout/cart";
Mage::getSingleton('checkout/session');
Mage::getSingleton('customer/session')->loginById($params['customer_id']);//login the customer, so that we add items to this customers' cart and then redirect them to their cart.
 
$productIds=$params['product_id'];
 
            try{
                $cart = new Mage_Checkout_Model_Cart();
                $cart->truncate();//clear existing cart items
                $cart->init();
                $cart->addProductsByIds($productIds);
                $cart->save();
            }
            catch(Exception $e){
                echo $e->getMessage();
            }
 
$this->_redirect($redirect);

Happy coding!