Magento 1.9 Add to Cart – Custom Option

addtocartmagento-1.9product-attribute

I need help in adding cart with the additional custom option included on it

I've looked around stackoverflow and stackexchange for the answer but sadly it failed and they only add product simply, and without its custom option.

this however https://stackoverflow.com/questions/13698236/add-product-to-cart-with-custom-options sounds that possibly might work. but my problem is, i do not know the singleTon or Helper declared in the variable $quoteItem

any help will do, thanks! 🙂

Here's my script just in case:

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

$addItem = array(
                 'product' => $product_id,
                 'qty' => $qty,
                 'options' => array("Color"  => $color)
                );                               

$_product   = Mage::getSingleton('catalog/product')->load($product_id);
$cart->addProduct($_product, new Varien_Object($addItem));
$cart->save();

Best Answer

i finally figured it out

In adding an custom option, you don't use the custom option's label as the key of the array value (which in my case $color is the array value and 'color' is the label).
But instead use the correspondent ID of that custom option you earlier set in the catalog settings.

so instead of
'options' => array("Color" => $color)
we will use
'options' => array( 1 => $color)

if you are unsure of your custom option id and want to get it, you can do it with this guy's script
http://blog.ansyori.com/magento-get-product-custom-options-label-id/

now for the code:

$productCollection = Mage::getModel('catalog/product')->load($product_id);

$cart->addProduct($productCollection ,
array( 'product_id' => $product_id,
       'qty' => $qty,
       'options' => array( 1 => $color)
     ));
$cart->save();