Adding Multiple Products To The Cart Simultaneously

In a previous post I looked at creating a product on the fly and adding it to the cart automatically. However, if you are using Magento without the catalog then when you transfer customers from your catalog to the cart and checkout you may need to create and add multiple products to the cart.

Creating multiple products is fairly straightforward if you use my methodology for creating a single product from the previous post. To add multiple products to the cart, create the products and add the product objects to an array, here I have named it $products.

To then add all of these products to the cart simultaneously use the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
require_once ('app/Mage.php');
Mage::app();
$session = Mage:getModel('core/session', array('name' => 'frontend');
 
// create products here and add the objects to the array $products
$ids = array();
 
foreach ($products as $product)
{
 
     $ids[] = $product->getID();
 
}
 
$cart = Mage::getModel('checkout/cart');
$cart->addProductsByIDs($ids);
$cart->save();
 
// change to relevant URL for your store!
header("location: http://localhost/magento/checkout/cart/");

2 Responses to “Adding Multiple Products To The Cart Simultaneously”

Comments

  1. wriggles  on May 26th, 2009

    Hi,

    I tried this code but whenit redirects to the shopping cart, the basket is still empty. Can you suggest why this might be?

    Thanks,

    Matt

  2. jalexander  on December 28th, 2009

    wriggles: The problem is they don’t have a session started yet. You’d need to start a new session and then add the items and then you should be good.

Trackbacks/Pingbacks

Leave a Reply