Magento 1.9 – Programmatically Add Custom Options to Products

custom-optionsmagento-1.9product

Hi I am developing a script which makes simple products for magento store. I have added the products through the script but now I want to add custom options to the added simple product. How would I do it through my custom script? Here is how I am adding the product:

$product = Mage::getModel('catalog/product');
$product
        ->setStoreId($store_id) //you can set data in store scope
        ->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
        ->setAttributeSetId(4) //ID of a attribute set named 'default'
        ->setTypeId('simple') //product type
        ->setCreatedAt(strtotime('now')) //product creation time
->setWeight(1.0000)
        ->setStatus(1) //product status (1 - enabled, 2 - disabled)
        ->setTaxClassId(0) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
        ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //catalog and search visibility
->setHasOptions(true);
    $product->save();

After this code I want to add the custom options to this added product. How can I do it? Any help would be greatly appreciated. Thankyou.

Best Answer

Before $product->save(), you can add some code to save. Here's some good guides on how it works and what you need to write. HERE and HERE

Basically...

$options = array(...); // Look at guides how to create this array
$product->setCanSaveCustomOptions(true);
$product->getOptionInstance()->addOption($option);
$product->setHasOptions(true);