While development or testing, you may need a huge amount of products. Magento 2 has the feature to create the products from the backend but there is the time at which you want to create multiple products to test page performance, you need to create products in a certain format, you have some custom attribute or you have created your own attribute set or product type. It’s when you need to create products programmatically to ease the task and save the time. Here, I’ve come up with the custom code to implement to create a simple product programmatically in Magento 2!
There are six product types in Magento 2:
- Simple Product
- Configurable Product
- Grouped Product
- Virtual Product
- Bundle Product
- Downloadable Product
The below method allows creating simple product programmatically along with custom options. Moreover, you can add images to the media gallery of the product with the below method.
Create a Simple Product Programmatically in Magento 2:
<?php use Magento\Framework\App\Bootstrap; require 'app/bootstrap.php'; $bootstrap = Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager(); $state = $objectManager->get('\Magento\Framework\App\State'); $state->setAreaCode('frontend'); $product = $objectManager->create('Magento\Catalog\Model\Product'); try { $product->setName('Test Product'); $product->setTypeId('simple'); $product->setAttributeSetId(4); $product->setSku('test-SKU'); $product->setWebsiteIds(array(1)); $product->setVisibility(4); $product->setPrice(array(1)); $product->setImage('/testimg/test.jpg'); $product->setSmallImage('/testimg/test.jpg'); $product->setThumbnail('/testimg/test.jpg'); $product->setStockData(array( 'use_config_manage_stock' => 0, 'manage_stock' => 1, 'min_sale_qty' => 1, 'max_sale_qty' => 2, 'is_in_stock' => 1, 'qty' => 100 ) ); $product->save(); // Adding Custom option to product $options = array( array( "sort_order" => 1, "title" => "Custom Option 1", "price_type" => "fixed", "price" => "10", "type" => "field", "is_require" => 0 ), array( "sort_order" => 2, "title" => "Custom Option 2", "price_type" => "fixed", "price" => "20", "type" => "field", "is_require" => 0 ) ); foreach ($options as $arrayOption) { $product->setHasOptions(1); $product->getResource()->save($product); $option = $objectManager->create('\Magento\Catalog\Model\Product\Option') ->setProductId($product->getId()) ->setStoreId($product->getStoreId()) ->addData($arrayOption); $option->save(); $product->addOption($option); } } catch (\Exception $e) { echo $e->getMessage(); }
That’s it and we have created a simple product quickly! If you still can’t see it on the frontend, reindex and clear your cache.
If you opt to create simple product in Magento 2 from the admin panel, refer our blog post.
Happy Coding!