Create products programmatically in magento

When developing a magento website sometimes you need to update or create products from code directly. The code below helps you to create simple product programmatically.

But still you can upload products from magento import/export from admin. There are some attributes you need to define and set when creating products. You need to set attribute set, product type, sku, name, weight, status visibility, price, images, inventory etc.

try {
    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
    $simple = Mage::getModel('catalog/product');
    $simple
        ->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
        ->setAttributeSetId(2) //ID of a attribute set named 'default'
        ->setTypeId('simple') //product type
        ->setCreatedAt(strtotime('now')) //product creation time
        ->setSku('test') //SKU
        ->setName('test product') //product name
        ->setWeight(9.00)
        ->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED) //product status (1 - enabled, 2 - disabled)
        ->setTaxClassId(4) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
        ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //catalog and search visibility
        ->setPrice(99.99) //price in form 11.22
        ->setDescription('This is a long description')
        ->setShortDescription('This is a short description')
        ->setMediaGallery (array('images'=>array (), 'values'=>array ())) //media gallery initialization
        ->setStockData(array(
                           'manage_stock'=>1, //manage stock
                           'is_in_stock' => 1, //Stock Availability
                           'qty' => 10 //qty
                       )
        )
        ->setCategoryIds(array(2, 5)); //assign product to categories
    $simple->save();
}catch(Exception $e){
    Mage::log($e->getMessage());
}

You can also add images to product by following code:

$images = array(
    'thumbnail'   => 'image.jpg',
    'small_image' => 'image.jpg',
    'image'       => 'image.jpg',
);
 
$dir = Mage::getBaseDir('media') . DS . 'import/';
 
foreach ($images as $imageType => $imageFileName) {
    $path = $dir . $imageFileName;
    if (file_exists($path)) {
        try {
            $simple->addImageToMediaGallery($path, $imageType, false);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    } else {
        echo "Can not find image by path: '{$path}'";
    }
}

You can also use this code under observer, controller action etc. You can create other product types by updating the type id.

For configurable products, bundle products and group products you need to assign the simple products either manually or programatically.

For configurable product you can assign simple products by following steps:
First select configurable attributes:

$colorAttributeId = Mage::getModel('eav/entity_attribute')->getIdByCode('catalog_product', 'color');
$configurable->getTypeInstance()->setUsedProductAttributeIds(array($colorAttributeId));

Then collect the information of simple products:

$configurableProductsData = array();
$configurableAttributesData = $configurable->getTypeInstance()->getConfigurableAttributesAsArray();
 
$simpleProductsData = array(
    'label'         => $simple->getAttributeText('color'),
    'attribute_id'  => $colorAttributeId,
    'value_index'   => (int) $simple->getColor(),
    'is_percent'    => 0,
    'pricing_value' => $simple->getPrice(),
);
 
$configurableProductsData[$simple->getId()] = $simpleProductsData;
$configurableAttributesData[0]['values'][] = $simpleProductsData;

Set data to configurable product:

$configurable->setConfigurableProductsData($configurableProductsData);
$configurable->setConfigurableAttributesData($configurableAttributesData);

Then finally save the configurable product with special flag:

$configurable->setCanSaveConfigurableAttributes(true);
$configurable->save();

Hope this helps.
Cheers!!

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *