magento web developer


Manchester based Magento and Zend Framework certified developer.

Add products to the cart (in code)

Sometimes it is quite useful to be able to add products to a customer’s cart in code.  For example, you may wish to launch an email promotion with a link to the store. When the user clicks the link, they are directed straight to the cart page on the merchant’s website with the promoted product already in their cart!

Simple Products

Adding simple products is very easy and can be achieved with the following code:

// ...
$cart = Mage::getSingleton('checkout/cart');
$product = Mage::getModel('catalog/product')
    ->load(1234);

$cart->addProduct($product);
// or...
$cart->addProduct(1234);

$cart->save();
// ...

Configurable Products

Things get a bit more complex when you need to add a configurable product and you need to prepare a ‘request’ array with the following structure.

'super_attribute' =>
    [attribute_id] => [attribute_value_id],
    [attribute_id_2] => [attribute_value_id_2],
    ...
'qty' => [qty]

First up, you need to obtain the attribute id and attribute value id.

$attribute = Mage::getModel('catalog/product')
    ->getResource()
    ->getAttribute('color');

$attributeId = $attribute->getId();
$attributeValueId = $attribute
    ->getSource()
    ->getOptionId('blue');

And then implement the structure in PHP as follows:

$cart = Mage::getSingleton('checkout/cart');

$request = array();
$request['qty'] = 1;
$request['super_attribute'] = array();
$request['super_attribute'][65] = 1;
$request['super_attribute'][66] = 12;

$cart->addProduct(1242, $request);
$cart->save();