How to Programmatically Add Custom Options to All Products Without Duplication in Magento

custom-optionsmagento-1programmatically

I have over 40,000 products in store and am trying to add custom options to all. The script below works fine, but stops after about 1000 products, then starts again.. making duplicates rather than continuing to next products.

What would be the best way to check if product has option with title "Request Samples?". If so, skip and go to next (if else statement)?

Here is the code I have:

require_once 'app/Mage.php';
umask(0);

Mage::app('admin');

set_time_limit(0);

$option = array(
    'title' => 'Request Samples?',
    'type' => 'drop_down', 
    'is_require' => 0,
    'sort_order' => 0,
    'values' => getOptions()
    );

$collection = Mage::getModel('catalog/product')->getCollection();

foreach ($collection as $product_all) {


        $sku = $product_all['sku'];

        // retrieve product id using sku
        $product_id = Mage::getModel('catalog/product')->getIdBySku($sku);

        //Add option for to all products
        $product = Mage::getModel('catalog/product')->load($product_id);
        $optionInstance = $product->getOptionInstance()->unsetOptions();
        $product->setHasOptions(1);
        $optionInstance->addOption($option);
        $optionInstance->setProduct($product);
        $product->save();
        unset($product);
        echo "Done";
}

    function getOptions(){
       return array(
       array(
        'title' => 'Yes',
        'price' =>0,
        'price_type' => 'fixed',
        'sku' => 'samples001',
        'sort_order' => '1'
        )
    );
}

Best Answer

To get Products which has option with title Request Samples?, please use below code.

$Option=Mage::getModel('catalog/product_option')->getCollection();
$Option->getSelect()->joinLeft( array('option_title'=> Mage::getSingleton('core/resource')->getTableName('catalog/product_option_title')), 'main_table.option_id = option_title.option_id',array('title'))->where('option_title.title = ?','Request Samples?');

$products = $Option->getColumnValues('product_id');

This will give you all the products which has option added with title Request Samples?

Now you can filter your product collection which does not have above products.

$collection = Mage::getModel('catalog/product')->getCollection()
             ->addAttributeToFilter('entity_id', array('nin'=>$products));

This will give you all products which does not have custom option added already. Then you can loop through these products and add the option.