Create simple products in magento programmatically

This tutorial explains how to create simple products in magento programmatically.

Step by step explanation.

  1. Read data from CSV
  2. Create Simple Product
  3. Set default and additional images
  4. Add Tier Prices

Create Simple Product

For creating the simple product in this tutorial I am reading the data from the csv file (please click here to download the sample products.csv file).

Read data from CSV

Click here to reads the data from the csv and get the result in an array ($arrResult).

/**
 * Get product info from products.csv
 */
function getProducts()
{
    $arrResult = array();
    $file = 'csv/products.csv';
    $handle = fopen($file, "r");
    $headers_products = false;
    if (empty($handle) === false) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            if (!$headers_products) {
                $headers_products[] = $data;
            } else {
                $arrResult[] = $data;
            }
        }
        fclose($handle);
    }
    return $arrResult;
}

The array contains the following details.

create simple products magento

Create the simple product

The saveSingleProduct() function creates the simple product. The simple product accept the following paramaters.

  1. $import_product – contains the details we read from the CSV
  2. $sku – this variable pass the sku values.If it is null it create an unique value as shown below.
    if ($import_product[3] == '' || $import_product[3] == null) {
                $sku = $dummy_sku . $dummy_sku_counter++;
            } else {
                $sku = $import_product[3] . $dummy_sku_counter++;
            }
  3. $enabled -set the product status.
     if (strtolower($import_product[22]) == true) { //status
                $enabled = 1;
            } else {
                $enabled = 2;
            }
  4. $visible – for single product set the visible variable to VISIBILITY_BOTH as shown below.
     $visible = Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH;
    
  5. $migrated_categories – contains the category ids . ( While importing the data from the CSV we imported the categories initially. So we need to retreieve the new category id from the old category id. Please refer the import category tutorial for more details )
  6. $discount_arr – This array contains the values for creating the tier prices.Please refer add tier pries tutorial.
function saveSingleProduct($import_product,$sku,$enabled,$visible,$migrated_categories,$discount_arr,$dir) {
    
     try {
        $tierPrices = array();
        $product = Mage::getModel('catalog/product');
      
        $product->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
                ->setAttributeSetId(4)  //ID of a attribute set named 'default'
                ->setTypeId('simple') //product type
                ->setCreatedAt(strtotime('now')) //product creation time
                ->setSku($sku) //SKU
                ->setName($import_product[1]) //product name
                ->setWeight($import_product[16])
                ->setStatus($enabled) //product status (1 - enabled, 2 - disabled)
                ->setTaxClassId(0) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
                ->setVisibility($visible)//catalog and search visibility
                ->setPrice($import_product[11])//price in form 11.22
                ->setCost(1)//price in form 11.22              
                ->setMetaTitle($import_product[1])
                ->setMetaKeyword($import_product[26])
                ->setMetaDescription($import_product[28])
                ->setDescription($import_product[27])
                ->setShortDescription($import_product[27])
                ->setStockData(array(
                        'use_config_manage_stock' => 1, //'Use config settings' checkbox
                        'is_in_stock' => 1, //Stock Availability
                        'qty' => (int)$import_product[6] //qty
                    )
                )
                ->setCategoryIds( $migrated_categories); //assign product to categories
        
     
        if ($product->save()){ //($product->save()) {
            echo 'Single Product ' . $product->getName() . ' ' . $product->getId() . ' imported successfully' . PHP_EOL;
        }
          
        } catch (Exception $e) {
            Mage::log($e->getMessage());
        }
        return array($import_product[0],$product->getId(), $import_product[33]);
}

Add Product Images

Please click here to get the detail explanation.

 $importDir = Mage::getBaseDir('media') . DS;
 
 // main image
        if ($mainImage) {
            $image_directory = $dir . DS . 'data' . DS . $mainImage;
            if (file_exists($image_directory)) {
                $product->setMediaGallery(array('images' => array(), 'values' => array()))//media gallery initialization
                ->addImageToMediaGallery($image_directory, array('image', 'thumbnail', 'small_image'), false, false);//assigning image, thumb and small image to media gallery

            } else {
                $image_directory = $dir . 'data' . DS . 'comingsoon.jpg';
                $product->setMediaGallery(array('images' => array(), 'values' => array()))//media gallery initialization
                ->addImageToMediaGallery($image_directory, array('image', 'thumbnail', 'small_image'), false, false);
            }
        }

Additional Product Images

Please click here to get the detail explanation.

$importDir = Mage::getBaseDir('media') . DS;
 // additional images
        if ($import_product[29] != '') {
            $addImages = explode(",", trim($import_product[29]));
            foreach ($addImages as $additional_image) {
                $image_directory = $dir .DS.'data'.DS. trim($additional_image);
                if (file_exists($image_directory)) {
                    $product->addImageToMediaGallery($image_directory, null, false, false);
                } else {
                    $image_directory = $dir . 'data' . DS . 'comingsoon.jpg';
                    $product->addImageToMediaGallery($image_directory, null, false, false);
                }
            }
            echo 'Additional images for product ' . $product->getName() . ' ' . $product->getId() . ' imported successfully' . PHP_EOL;
        }

import-categories-magento
import-simple-products-magento
If you have any further queries please leave a reply.

Share this Tutorial

Leave a Reply

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

*