Magento : Add Custom Option for all products programmatically

No comments
If you have a large number products in your project and you want to add a custom option in each product then what will you do? Either you will create required option one by one for each product into your Magento admin, or you will search for a solution, so that you can add required options in your products. So here is the solution. In this tutorial, I am going to add a text area in my each product with character limits to 1000, price 0.00 and sort order to 0.

First of all, create a PHP file in your project root folder and name it ‘myoptions.php’ and then paste below code into the file.

require_once 'app/Mage.php';
$option = array(
            'is_delete' => 0,
            'title' => 'Comments',
            'previous_group' => '',
            'previous_type' => '',
            'type' => 'area',
            'is_require' => 0,
            'sort_order' => 0,
            'price' => 0,
            'price_type' => 'fixed',
            'max_characters' => 1000,
            'values' => array(),
$categoryIds = array(6,7);//category ids separated by comma
$collection = Mage::getModel('catalog/product')
                             ->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
                             ->addAttributeToFilter('category_id', array('in' => $categoryIds));
foreach ($collection as $products) {
        $sku = $products['sku'];
        $product_id = Mage::getModel('catalog/product')->getIdBySku($sku);
        $product = Mage::getModel('catalog/product')->load($product_id);

        //Now save the product
        echo "Done".$sku;

And then run this file. And now, you will see the custom options are added in each product.

Here $categoryIds is an array variable where you can set the category ids if you want to add options for a specific category. Otherwise, leave it blank and remove addAttributeToFilter('category_id', array('in' => $categoryIds)); from your code. Note that, removing these lines from your code will add custom options in each product.

No comments :

Post a Comment