Magento 2: Create Product Programmatically

Creating more products in the admin is time taking and panic. Coding here which helps to create products running through command or hit in browser or setup in CRON so that it automatically create products. You can also use this for getting products data from a CSV and import into Magento. Scripting here in detail like writing all information in log which helps to debug data.

<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Change path according to your import file
require __DIR__ . '/../app/bootstrap.php';

use Magento\Framework\App\Bootstrap;

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

//website URL : http://www.example.com
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');        
$baseUrl = $storeManager->getStore()->getBaseUrl(); 

// Log
$logfile = 'import-product-'.date('Y-m-d-H-i').'.log';
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/'.$logfile);
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);

try {	

	$logger->info('############ Start import processing......................');
				
	$rows = array('test1','test2');
	$num = count($rows);
	echo "Total number of products:". $num;
	$logger->info('Total number of products: '.$num);
	
	$i = 1;
	foreach($rows as $productData){
		echo "<pre>";
		$name = $productData;
		$sku = $productData;
		$description = $productData;
		$price = '10';
		//print_r($productData);exit;
		//$logger->info($productData);

		// Existing product
		$prodCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');

		$collection = $prodCollection->create()
				->addAttributeToSelect('*')
				->addFieldToFilter('sku',$sku);
					 
		$productExistingId  = false;
		if ($collection->getSize()) {
			$productExistingData = $collection->getFirstItem();		
			//$productExistingSku = $productExistingData->getSku();	
			$productExistingId = $productExistingData->getId();				
		}
		// End of Existing product

		/*
		* Custom query: check url key
		*/
		$resources = $objectManager->get('Magento\Framework\App\ResourceConnection');
		$connection= $resources->getConnection();

		$urlKey = preg_replace('#[^0-9a-z]+#i', '-', $name);
    	$urlKey = strtolower($urlKey);
    	$urlKey = trim($urlKey, '-');

		$pathUrl = $urlKey.'.html';
		$tableName = $resources->getTableName('url_rewrite');
		/**/
		$select = $connection->select()
			->from(
				['o' =>  $tableName]
			)
			->where('o.request_path=?',$pathUrl)
			;

		/**/	

		$result = $connection->fetchAll($select);

		// end of url key //////////////
		
		$productSave = false;
		if(count($result) == 0){
			$productSave = true;			
		}
		elseif(count($result) == 1){
			if($productExistingId == $result[0]['entity_id'])
			{
				$productSave = true;				
			}
		}
		else{			
			$productSave = false;			
		}

		
		if($productSave)
		{
						
			$_product = $objectManager->create('Magento\Catalog\Model\Product');
			$_product->setName($name);
			$_product->setTypeId('simple');
			$_product->setAttributeSetId(1); // 1=>Default
			$_product->setSku($sku);
			$_product->setDescription($description); // description of product
			$_product->setShortDescription($description);			
			$_product->setWebsiteIds(array(1));
			$_product->setVisibility(4);			
			$_product->setPrice($price);
			//////////status
			$_product->setStatus(1);
			//$_product->setStatus(Status::STATUS_ENABLED);
			//end of status //Status::STATUS_ENABLED:Status::STATUS_DISABLED
			
			$productImage = '/import/test-product.jpg';// Path pub/meida/catalog/product/test.jpg
			
			//$importDir = __DIR__ . '/../pub/media/import/';

			$_product->addImageToMediaGallery($productImage, array('image', 'small_image', 'thumbnail'), false, false); // Add Image 1
	   		// $_product->addImageToMediaGallery($productImage, array('image', 'small_image', 'thumbnail'), false, false); // Add Image 2    
	          

			$_product->setCategoryIds(array(3,4,7,8,9));
			$_product->setStockData(array(
					'use_config_manage_stock' => 0, //'Use config settings' checkbox
					'manage_stock' => 1, //manage stock
					'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
					'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
					'is_in_stock' => 1, //Stock Availability
					'qty' => 9000 //qty
					)
				);
					
			$urlKey = '';
			$_product->setUrlKey($urlKey); // Dynamic Url key
			
			if($productExistingId){
				$_product->setId($productExistingId);
				$importType = 'UPDATED';
			}else{
				$importType = 'CREATED';
			}
			
			
			$_product->save();

			echo ('## #Row: ' . $i . ' #MagentoId: '.$_product->getId().' #Status: '. $importType .' #SKU: '.$_product->getSku());
			$logger->info('## #Row: ' . $i . ' #MagentoId: '.$_product->getId().' #Status: '. $importType .' #SKU: '.$_product->getSku()				
				);

		} // endif check status for product save

		//echo "<pre>";
		//print_r($_product->getName());
		 
		
		$i++;
		
	} // end of foreach

	// Unset
	unset($dbh);
	unset($stmt);


} // end of try
catch(Exception $e) {
    //print_r($e->getMessage());
	$logger->info('##ERROR: '.$e->getMessage());
}


$logger->info('||||| Completed ||||| ');

echo "<br><br><a target='_blank' href='". $baseUrl ."var/log/".$logfile."'> View log</a><br><br>";