Programmatically Add Grouped Product to Cart in Magento


Programmatically Add Grouped Product to Cart in Magento

Adding simple products to cart through custom PHP code is pretty straight forward. You just need to call the ‘$cart->addProduct()’ function with the product_id and quantity as parameters. But if you want to add grouped products to cart through your code, you will need to perform few additional steps. The process is very easy – create an ‘$super_group’ array of the associated products with the specified quantities. Then you need to pass the array to the ‘addProduct()’ function. See the actual code below that makes it work:

//Array for holding the associated products
$super_group = array();

//Id of the grouped product
$parentId = <grouped_product_id>;

//Create an array of associated products
$children = array('<child_id_1>','<child_id_2>','<child_id_3>');

//Quantity of each child product to be addede to cart
$child_qty = 2;

//Add all child products to $super_group with product_id as key and quantity as value
foreach($children as $child){
   $super_group[$child] = $child_qty;

//Add Grouped product to cart
try {
 //Get object of main grouped product
 $product = Mage::getModel('catalog/product')->load($parentId);

 //Check product availability
 if (!$product) {
  echo "Error in product!";

 //Get cart object
 $cart = Mage::getModel('checkout/cart');

 //Create params for grouped product
 $params = array('super_group' => $super_group);

 //Add product to cart with specified parameters and save the cart object
 $cart->addProduct($product, $params)->save();


 echo $this->__('%s was added to your shopping cart.', Mage::helper('core')->htmlEscape($product->getName()));

catch (Mage_Core_Exception $e){
 if (Mage::getSingleton('checkout/session')->getUseNotice(true)){
  echo $this->__($e->getMessage());
  $messages = array_unique(explode("\n", $e->getMessage()));
  foreach ($messages as $message) {
   echo "<br />".$message;
catch (Exception $e){
 echo $this->__('Cannot add the item to shopping cart.');

Leave a Reply

You must be logged in to post a comment.