Magento how to programmatically create products


Step 1: Define Function


Magento 1


class MageCheck_Tutorial_IndexController extends Mage_Core_Controller_Front_Action { public function indexAction() { $this-> createProduct(); } public function createProduct() { // ... } }

Magento 2


/** * @var object \Magento\Catalog\Model\Product $product */ protected $_product; public function __construct( \Magento\Catalog\Model\Product $product ){ $this->_product = $product; } public function execute() { $this->creatingProduct(); } public function creatingProduct() { // ... }

Step 2: Create Function


Magento 1


public function createProduct() { Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); $product = Mage::getModel('catalog/product'); try { $product ->setWebsiteIds(array(1)) ->setAttributeSetId(9) ->setTypeId('simple') ->setCreatedAt(strtotime('now')) ->setSku('testsku61') ->setName('test product21') ->setWeight(4.0000) ->setStatus(1) ->setTaxClassId(4) ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) ->setManufacturer(28) ->setColor(24) ->setPrice(11.22) ->setCost(22.33) ->setSpecialPrice(00.44) ->setMsrpEnabled(1) ->setMsrpDisplayActualPriceType(1) ->setStockData(array( 'use_config_manage_stock' => 0, 'manage_stock' => 1, 'min_sale_qty' => 1, 'max_sale_qty' => 2, 'is_in_stock' => 1, 'qty' => 999 ) ) ->setCategoryIds(array(3, 10)); $product->save(); } catch (Exception $e) { Mage::log($e->getMessage()); } }

Magento 2


public function creatingProduct() { $product = $this->_product; $product->setSku('my-sku'); $product->setName('Example Product'); $product->setAttributeSetId(4); $product->setStatus(1); $product->setWeight(10); $product->setVisibility(4); $product->setTaxClassId(0); $product->setTypeId('simple'); $product->setPrice(100); $product->setStockData( array( 'use_config_manage_stock' => 0, 'manage_stock' => 1, 'is_in_stock' => 1, 'qty' => 999999999 ) ); $product->save(); }