Wednesday, September 5, 2012

Add attribute option programmatically in magento

 You can easily create attribute options from outside magento using following code :

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

function addAttributeOption($attribute_code, $attribute_value) {
    $attribute_model = Mage::getModel('eav/entity_attribute');
    $attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
   
    $attribute_id = $attribute_model->getIdByCode('catalog_product', $attribute_code);
    $attribute = $attribute_model->load($attribute_id);
   
    $attribute_table = $attribute_options_model->setAttribute($attribute);
    $options = $attribute_options_model->getAllOptions(false);

   foreach($options as $option) {
        // checking if already exists
        if ($option['label'] == $attribute_value) {
$optionId = $option['value'];
                return $optionId;
        }
    }

    $value['option'] = array($attribute_value,$attribute_value);
    $result = array('value' => $value);
    $attribute->setData('option',$result);
    $attribute->save();
}

addAttributeOption('color','white');

?>

Note : In this example I've added an option "white" to an attribute "color" of select type.