Engine23
blogBannerImage
By Engine23

Magento Programmatically add an item to the cart with custom options

Lest say you have a need in your Magento store to have an "auto add to cart". This would be in situations where maybe you provide a free sample if they purchase a specific product, or maybe you will attach a warranyt sku to specific products automatically. However, this item your adding to the magneto cart has custom options! This can be tricky. Here is an example function I use when I run into this situation.

 
    protected function _saveCustomOption($product_id, $product, $qty)
    {
        // Load up a product that has the custom options and get the attributes, in this case we just have one custom option
       // This custom option is a text field and our end goal is to populate that with sku-product name
        $_product   = Mage::getSingleton('catalog/product')->load($product_id);
        $attrs      = $_product->getOptions();
        foreach($attrs as $attr)
        {
           // Loop through all the custom options ( once again we only have one in our scenario ) and assign the values we need
          // The $att->getData('option_id') is the custom option ID that we are assigning our sku-product name to
          // The qty is passed in but you can hard code it, or make it not required and just omit that
            $params = array(
                'product' => $product_id,
                'qty' => $qty,
                'options' => array(
                    $attr->getData('option_id')  => $product->getData('sku') . '-' . $product->getData('name')
                )
            );

        }
       // I always try to use a try/catch this way you can see the error in your step-through-debugger 
        try{
            // Load the cart, add the product, and save!  You can also update the cart to say it was updated, but that is not required
            $cart = Mage::getSingleton('checkout/cart');
            $cart->addProduct($_product, $params);
            $cart->save();
            Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
        } catch( Exception $e) {
            $error = $e;
        }

    }

If something is not working you can reach out to our Magento support team.