Adding a new product

Last modified by go_golfing_now on Tue, August 30, 2011 17:58
Source|Old Revisions  

This is an old revision of the document!


Here is how you can add a product using Magento backend.

//create a new product
try {
  $newProduct = Mage::getModel('catalog/product')
    ->setStoreId('default')
    ->setCategoryIds('4')
    ->setAttributeSetId(41)
    ->setPrice(15.49)
    ->setSku('4you')
    ->setName('4You T Shirt')
    ->setManufacturer(20)
    ->setTypeId('simple')
    ->save(); 
    
  echo 'OK Product ID: '.$newProduct->getId();
}
catch (Mage_Core_Exception $e) {
  echo $e->getMessage();
}
catch (Exception $e) {
  echo $e;
}

You can set any other attribute by using universal setter function setData($attribute_code, $value) or for example for shirt size: setShirtSize($value). Varian object translates it automatically into setData(’shirt_size’, $value).

If you want to update existing product, call $newProduct→load($id) before setting any attributes.


Edit: Thanks to Bojan for this article. I tried this with Magento 1.3.2.3 and realized after some searching that there is the product type id missing, which is required to add a product. So i added this “→setTypeId(’simple’)” to save others people time to search.


To add an image to the products galery add this method to the code above: addImageToMediaGallery($file, $mediaAttribute, $move, $exclude)

@param string $file file path of image in file system

@param string|array $mediaAttribute code of attribute with type ‘media_image’, leave blank if image should be only in gallery

@param boolean $move if true, it will move source file

@param boolean $exclude mark image as disabled in product page view




 

Magento 2 GitHub Repository

Magento Job Board - Some sort of tag line goes here

Latest Posts| View all Jobs