Saturday, November 28, 2015

Add new product programmatically in Magento


In Magento development sometimes you need to add product from front end or outside of Magento folder than must add new product as programmatically. Magento provides added product features from admin panel so you can add different types of products from admin panel according to requirement. In Magento there are six types of products
  • Simple Products
  • Grouped Products
  • Configurable Products
  • Virtual Products
  • Bundled Products
  • Downloadable Products
Here below display code for adding product as programmatically according to different product types. For that you much create any PHP file in the Magento root directory by adding `app/Mage. php` file. If you want to add below code in Mageto theme files, then no need to add `Mage.php` file.

SIMPLE PRODUCT / VIRTUAL PRODUCT


require_once "app/Mage.php";
if (!Mage::isInstalled())
{
  echo "Application is not installed yet, please complete install wizard first.";exit;
}
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$simpleproduct = Mage::getModel('catalog/product');
$simpleproduct->setName('PRODUCT NAME');
$simpleproduct->setSku('PRODUCT SKU');
$simpleproduct->setShortDescription('SHORT DESCRIPTION');
$simpleproduct->setDescription('PRODUCT FULL DESCRIPTION');
$simpleproduct->setTypeId('simple'); //set product type
$simpleproduct->setWeight(0); //set product weight
$simpleproduct->setNewsFromDate('08-20-2014'); //product set as new from
$simpleproduct->setNewsToDate('09-20-2014'); //product set as new to
$simpleproduct->setPrice(10.01); //set product price
$simpleproduct->setSpecialPrice(00.44); //set product special price
$simpleproduct->setSpecialFromDate('08-20-2014'); //special price from (MM-DD-YYYY)
$simpleproduct->setSpecialToDate('09-20-2014'); //special price to (MM-DD-YYYY)
$simpleproduct->setMsrpEnabled(1); //apply MAP
$simpleproduct->setMsrpDisplayActualPriceType(4); //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
$simpleproduct->setMsrp(12.0); //manufacturer's suggested retail price
$simpleproduct->setTaxClassId(0); //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
$simpleproduct->setCreatedAt(strtotime('now'));
$simpleproduct->setCountryOfManufacture('IN'); //set 2 latters country name 
$simpleproduct->setAttributeSetId(Mage::getModel('catalog/product')->getResource()->getEntityType()->getDefaultAttributeSetId()); //set default attribute id
$simpleproduct->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId())); //get store website ids
$simpleproduct->setStatus(1); //product status (1 - enabled,2 - disabled)
$simpleproduct->setVisibility(4); //set product visibility (1 - Not Visible Individually,2 - Catalog,3 - Search,4 - Catalog, Search)
$stock_data=array(
   'use_config_manage_stock' => 1, //use config settings checkbox
   'qty' => trim(10), //quantity
   'min_qty' => 0, 
   'use_config_min_qty'=>1,
   'min_sale_qty' => 0, //minimum quantity allowed in shopping cart
   'use_config_min_sale_qty'=>1,
   'max_sale_qty' => 9999, //maximum quantity allowed in shopping cart
   'use_config_max_sale_qty'=>1,
   'is_qty_decimal' => 0,
   'backorders' => 0,
   'notify_stock_qty' => 1,
   'is_in_stock' => 1 //stock availability
 );
$simpleproduct->setData('stock_data',$stock_data);
$simpleproduct->setCategoryIds(array(2,3)); //assign categories to product
$simpleproduct->addImageToMediaGallery('C:\1.jpg', array('image','small_image','thumbnail'), false, false);
/*
addImageToMediaGallery function parameters
1) C:\1.jpg = ABSOLUTE IMAGE PATH
2) array('image','small_image','thumbnail') = 'IMAGE DEFINE AS MAIN IMAGE,SMALL AND THUMBNAIL'
3) flase = DO NOT MOVE PRODUCT(true for remove product from source)
4) false = DISPLAY PRODUCT IN FONTEND (true for exclude product in frontend)
*/
$simpleproduct->setMetaTitle('PRODUCT META TITLE');
$simpleproduct->setMetaKeyword('PRODUCT META KEYWORDS');
$simpleproduct->setMetaDescription('PRODUCT META DESCRIPTION');
$simpleproduct->save();


GROUPED PRODUCT


$groupedproduct = Mage::getModel('catalog/product');
$groupedproduct->setName('PRODUCT NAME');
$groupedproduct->setSku('PRODUCT SKU');
$groupedproduct->setShortDescription('SHORT DESCRIPTION');
$groupedproduct->setDescription('PRODUCT FULL DESCRIPTION');
$groupedproduct->setTypeId('grouped'); //set product type
$groupedproduct->setWeight(0); //set product weight
$groupedproduct->setNewsFromDate('08-20-2014'); //product set as new from
$groupedproduct->setNewsToDate('09-20-2014'); //product set as new to
$groupedproduct->setCreatedAt(strtotime('now'));
$groupedproduct->setCountryOfManufacture('IN'); //set 2 latters country name 
$groupedproduct->setAttributeSetId(Mage::getModel('catalog/product')->getResource()->getEntityType()->getDefaultAttributeSetId()); //set default attribute id
$groupedproduct->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId())); //get store website ids
$groupedproduct->setStatus(1); //product status (1 - enabled,2 - disabled)
$groupedproduct->setVisibility(4); //set product visibility (1 - Not Visible Individually,2 - Catalog,3 - Search,4 - Catalog, Search)
$stock_data=array(
   'is_in_stock' => 1 //stock availability
 );
$groupedproduct->setData('stock_data',$stock_data);
$groupedproduct->setCategoryIds(array(2,3)); //assign categories to product
$groupedproduct->addImageToMediaGallery('C:\1.jpg', array('image','small_image','thumbnail'), false, false);
/*
addImageToMediaGallery function parameters
1) C:\1.jpg = ABSOLUTE IMAGE PATH
2) array('image','small_image','thumbnail') = 'IMAGE DEFINE AS MAIN IMAGE,SMALL AND THUMBNAIL'
3) flase = DO NOT MOVE PRODUCT(true for remove product from source)
4) false = DISPLAY PRODUCT IN FONTEND (true for exclude product in frontend)
*/
$groupedproduct->setMetaTitle('PRODUCT META TITLE');
$groupedproduct->setMetaKeyword('PRODUCT META KEYWORDS');
$groupedproduct->setMetaDescription('PRODUCT META DESCRIPTION');
$groupedproduct->save();
$group_productid = $groupedproduct->getId(); //new saved grouped product id
Mage::getModel('catalog/product_link_api')->assign ("grouped",$group_productid,array(1,2)); //assign products as group


BUNDLE PRODUCT


$bundleproduct = Mage::getModel('catalog/product');
$bundleproduct->setName('PRODUCT NAME');
$bundleproduct->setSkuType(0); //product SKU type (0 - dynamic,1 - fixed)
$bundleproduct->setSku('PRODUCT SKU');
$bundleproduct->setShortDescription('SHORT DESCRIPTION');
$bundleproduct->setDescription('PRODUCT FULL DESCRIPTION');
$bundleproduct->setTypeId('bundle'); //set product type
$bundleproduct->setWeightType(0); //product weight type (0 - dynamic, 1 - fixed)
$bundleproduct->setWeight(0); //set product weight
$bundleproduct->setNewsFromDate('08-20-2014'); //product set as new from
$bundleproduct->setNewsToDate('09-20-2014'); //product set as new to
$bundleproduct->setPriceType(0); //price type (0 - dynamic,1 - fixed)
$bundleproduct->setPriceView(0); //price view (0 - price range,1 - as low as)
$bundleproduct->setSpecialPrice(1.0); //special price
$bundleproduct->setSpecialFromDate('08-20-2015'); //special price from (MM-DD-YYYY)
$bundleproduct->setSpecialToDate('09-20-2015'); //special price to (MM-DD-YYYY)
$bundleproduct->setCreatedAt(strtotime('now'));
$bundleproduct->setAttributeSetId(Mage::getModel('catalog/product')->getResource()->getEntityType()->getDefaultAttributeSetId()); //set default attribute id
$bundleproduct->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId())); //get store website ids
$bundleproduct->setStatus(1); //product status (1 - enabled,2 - disabled)
$bundleproduct->setVisibility(4); //set product visibility (1 - Not Visible Individually,2 - Catalog,3 - Search,4 - Catalog, Search)
$stock_data=array(
   'use_config_manage_stock' => 1, //use config settings checkbox
   'manage_stock' => 1, //manage stock
   'is_in_stock' => 1 //stock availability
 );
$bundleproduct->setData('stock_data',$stock_data);
$bundleproduct->setCategoryIds(array(2,3)); //assign categories to product
$bundleproduct->addImageToMediaGallery('C:\1.jpg', array('image','small_image','thumbnail'), false, false);
/*
addImageToMediaGallery function parameters
1) C:\1.jpg = ABSOLUTE IMAGE PATH
2) array('image','small_image','thumbnail') = 'IMAGE DEFINE AS MAIN IMAGE,SMALL AND THUMBNAIL'
3) flase = DO NOT MOVE PRODUCT(true for remove product from source)
4) false = DISPLAY PRODUCT IN FONTEND (true for exclude product in frontend)
*/
$bundleproduct->setShipmentType(0); //shipment type (0 - together, 1 - separately)
$bundleproduct->setMetaTitle('PRODUCT META TITLE');
$bundleproduct->setMetaKeyword('PRODUCT META KEYWORDS');
$bundleproduct->setMetaDescription('PRODUCT META DESCRIPTION');
$bundleoptions = array(
 '0' => array( //option array key (0,1,2,etc..)
  'title' => 'Option 0', //option title
  'option_id' => '',
  'delete' => '',
  'type' => 'select', //option type select,radio,checkbox,multi
  'required' => '1', //option is required or not (0 - not required,1- required)
  'position' => '1' //set option position
 )
);
$bundleselections = array(
        '0' => array( //option array key according to $bundleoptions
            '0' => array( //product list array key (0,1,2,etc..)
                'product_id' => '1', //product id
                'delete' => '',
                'selection_price_value' => '10', //selected option price
                'selection_price_type' => 0,
                'selection_qty' => 1, //selected product quantity
                'selection_can_change_qty' => 0, //user can chnage quantity (0 - NO,1 - YES)
                'position' => 0,
                'is_default' => 1 //set default selected option
            )
  )
 );
Mage::register('product', $bundleproduct);
Mage::register('bundleproduct', $bundleproduct);
$bundleproduct->setCanSaveConfigurableAttributes(false);
$bundleproduct->setCanSaveCustomOptions(true);
$bundleproduct->setBundleOptionsData($bundleoptions);
$bundleproduct->setBundleSelectionsData($bundleselections);
$bundleproduct->setCanSaveBundleSelections(true);
$bundleproduct->setAffectBundleProductSelections(true);
$bundleproduct->save();


CONFIGURABLE PRODUCT


$configurableproduct = Mage::getModel('catalog/product');
$configurableproduct->setName('PRODUCT NAME');
$configurableproduct->setSku('PRODUCT SKU');
$configurableproduct->setShortDescription('SHORT DESCRIPTION');
$configurableproduct->setDescription('PRODUCT FULL DESCRIPTION');
$configurableproduct->setAttributeSetId(13); // set same attribute id which is use for configure product
$configurableproduct->setWebsiteIds(array(1));
$configurableproduct->setTypeId('configurable'); //set product type
$configurableproduct->setWeight(0); //set product weight
$configurableproduct->setNewsFromDate('08-20-2014'); //product set as new from
$configurableproduct->setNewsToDate('09-20-2014'); //product set as new to
$configurableproduct->setPrice(10.01); //set product price
$configurableproduct->setSpecialPrice(00.10); //set product special price
$configurableproduct->setSpecialFromDate('08-20-2014'); //special price from (MM-DD-YYYY)
$configurableproduct->setSpecialToDate('09-20-2014'); //special price to (MM-DD-YYYY)
$configurableproduct->setMsrpEnabled(1); //apply MAP
$configurableproduct->setMsrpDisplayActualPriceType(4); //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
$configurableproduct->setMsrp(12.0); //manufacturer's suggested retail price
$configurableproduct->setTaxClassId(0); //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
$configurableproduct->setCreatedAt(strtotime('now'));
$configurableproduct->setCountryOfManufacture('IN'); //set 2 latters country name 
$configurableproduct->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId())); //get store website ids
$configurableproduct->setStatus(1); //product status (1 - enabled,2 - disabled)
$configurableproduct->setVisibility(4); //set product visibility (1 - Not Visible Individually,2 - Catalog,3 - Search,4 - Catalog, Search)
$stock_data=array(
   'use_config_manage_stock' => 1, //use config settings checkbox
   'is_in_stock' => 1 //stock availability
 );
$configurableproduct->setData('stock_data',$stock_data);
$configurableproduct->setCategoryIds(array(2,3)); //assign categories to product
//$configurableproduct->addImageToMediaGallery('C:\1.jpg', array('image','small_image','thumbnail'), false, false);
/*
addImageToMediaGallery function parameters
1) C:\1.jpg = ABSOLUTE IMAGE PATH
2) array('image','small_image','thumbnail') = 'IMAGE DEFINE AS MAIN IMAGE,SMALL AND THUMBNAIL'
3) flase = DO NOT MOVE PRODUCT(true for remove product from source)
4) false = DISPLAY PRODUCT IN FONTEND (true for exclude product in frontend)
*/
$configurableproduct->setMetaTitle('PRODUCT META TITLE');
$configurableproduct->setMetaKeyword('PRODUCT META KEYWORDS');
$configurableproduct->setMetaDescription('PRODUCT META DESCRIPTION');
$configurableproduct->getTypeInstance()->setUsedProductAttributeIds(array(92)); //set attribute id here 92 attribute id for 'color'
$configurableProductsData = array();
$configurableAttributesData = $configurableproduct->getTypeInstance()->getConfigurableAttributesAsArray();
 
$simpleProductsData = array(
    'label'         => 'Black', //attribute option label
    'attribute_id'  => 92, //set attribute id here 92 attribute id for 'color'
    'value_index'   => 10, //set value of selected color here 10 is value of 'Black' color
    'is_percent'    => 0, //set option price (0 - fixed,1 - percentage)
    'pricing_value' => 100, //selected option price
);
 
$configurableProductsData[10] = $simpleProductsData; // here 10 is configure product id which is match below attribute set and value. 
$configurableAttributesData[0]['values'][] = $simpleProductsData;
$configurableproduct->setConfigurableProductsData($configurableProductsData);
$configurableproduct->setConfigurableAttributesData($configurableAttributesData);
$configurableproduct->setCanSaveConfigurableAttributes(true);
$configurableproduct->save();


DOWNLOADABLE PRODUCT


$downloadableproduct = Mage::getModel('catalog/product');
$downloadableproduct->setName('PRODUCT NAME');
$downloadableproduct->setSku('PRODUCT SKU');
$downloadableproduct->setShortDescription('SHORT DESCRIPTION');
$downloadableproduct->setDescription('PRODUCT FULL DESCRIPTION');
$downloadableproduct->setTypeId('downloadable'); //set product type
$downloadableproduct->setWeight(0); //set product weight
$downloadableproduct->setNewsFromDate('08-20-2014'); //product set as new from
$downloadableproduct->setNewsToDate('09-20-2014'); //product set as new to
$downloadableproduct->setPrice(10.01); //set product price
$downloadableproduct->setSpecialPrice(00.44); //set product special price
$downloadableproduct->setSpecialFromDate('08-20-2014'); //special price from (MM-DD-YYYY)
$downloadableproduct->setSpecialToDate('09-20-2014'); //special price to (MM-DD-YYYY)
$downloadableproduct->setMsrpEnabled(1); //apply MAP
$downloadableproduct->setMsrpDisplayActualPriceType(4); //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
$downloadableproduct->setMsrp(12.0); //manufacturer's suggested retail price
$downloadableproduct->setTaxClassId(0); //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
$downloadableproduct->setCreatedAt(strtotime('now'));
$downloadableproduct->setCountryOfManufacture('IN'); //set 2 latters country name 
$downloadableproduct->setAttributeSetId(Mage::getModel('catalog/product')->getResource()->getEntityType()->getDefaultAttributeSetId()); //set default attribute id
$downloadableproduct->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId())); //get store website ids
$downloadableproduct->setStatus(1); //product status (1 - enabled,2 - disabled)
$downloadableproduct->setVisibility(4); //set product visibility (1 - Not Visible Individually,2 - Catalog,3 - Search,4 - Catalog, Search)
$stock_data=array(
   'use_config_manage_stock' => 1, //use config settings checkbox
   'qty' => trim(10), //quantity
   'min_qty' => 0, 
   'use_config_min_qty'=>1,
   'min_sale_qty' => 0, //minimum quantity allowed in shopping cart
   'use_config_min_sale_qty'=>1,
   'max_sale_qty' => 9999, //maximum quantity allowed in shopping cart
   'use_config_max_sale_qty'=>1,
   'is_qty_decimal' => 0,
   'backorders' => 0,
   'notify_stock_qty' => 1,
   'is_in_stock' => 1 //stock availability
 );
$downloadableproduct->setData('stock_data',$stock_data);
$downloadableproduct->setCategoryIds(array(2,3)); //assign categories to product
//$downloadableproduct->addImageToMediaGallery('C:\1.jpg', array('image','small_image','thumbnail'), false, false);
/*
addImageToMediaGallery function parameters
1) C:\1.jpg = ABSOLUTE IMAGE PATH
2) array('image','small_image','thumbnail') = 'IMAGE DEFINE AS MAIN IMAGE,SMALL AND THUMBNAIL'
3) flase = DO NOT MOVE PRODUCT(true for remove product from source)
4) false = DISPLAY PRODUCT IN FONTEND (true for exclude product in frontend)
*/
$downloadableproduct->setMetaTitle('PRODUCT META TITLE');
$downloadableproduct->setMetaKeyword('PRODUCT META KEYWORDS');
$downloadableproduct->setMetaDescription('PRODUCT META DESCRIPTION');
$downloadableproduct->setLinksTitle("Download");
$downloadableproduct->setLinksPurchaseType(0);//links can be purchased separately (0 - NO,1 - YES)
$downloadableproduct->setSamplesTitle("Sample");
$downloadableproduct->save();

$_highfilePath = "1.jpg";
$_samplefilePath = "2.jpg";
$paths = array('highurl' => $_highfilePath, 'sampleurl' => $_samplefilePath);
$samplefile[] = array(
  'file' => $_samplefilePath,
  'name' => $_samplefilePath,
  'size' => filesize($_samplefilePath),
  'status' => 'new'
);
$linkfile[] = array(
  'file' => $_highfilePath,
  'name' => $_highfilePath,
  'size' => filesize($_highfilePath),
  'status' => 'new'
);
$linkFileName = Mage::helper('downloadable/file')->moveFileFromTmp(Mage_Downloadable_Model_Link::getBaseTmpPath(),Mage_Downloadable_Model_Link::getBasePath(),$linkfile);
$linkModel = Mage::getModel('downloadable/link')->setData(array(
  'product_id' => $downloadableproduct->getId(),
  'sort_order' => 0, //set link order
  'number_of_downloads' => 0, // set numbers of download (0 - unlimited)
  'is_shareable' => 2, // shareable download link (0 - NO,1 - YES,2 - Use config) 
  'link_url' => '',
  'link_type' => 'file', //download link type url,file
  'link_file' => json_encode($linkfile),
  'sample_url' => 'http://www.site.com/1.jpg', //set sample file url
  'sample_file' => '', 
  'sample_type' => 'url', //download sample type url,file
  'use_default_title' => false, //title assign by user or not
  'title' => 'DOWNLOAD LINK TITLE',
  'default_price' => 0,
  'price' => 10, //add price for download links
  'website_id' => $downloadableproduct->getStore()->getWebsiteId(),
));
$linkModel->setLinkFile($linkFileName)->save();

$sampleFileName = Mage::helper('downloadable/file')->moveFileFromTmp(Mage_Downloadable_Model_Link::getBaseTmpPath(),Mage_Downloadable_Model_Link::getBasePath(),$samplefile);
$sampleModel = Mage::getModel('downloadable/sample')->setData(array(
  'product_id' => $downloadableproduct->getId(),
  'sort_order' => 0, //set sample order
  'sample_url' => 'http://www.site.com/1.jpg', //set sample file url
  'sample_file' => '', 
  'sample_type' => 'url', //sample file type url,file
  'title' => 'SAMPLE LINK TITLE',
  'website_id' => $downloadableproduct->getStore()->getWebsiteId(),
));
$sampleModel->setSampleFile($sampleFileName)->save();

No comments :

Post a Comment