With this tutorial, we'll bring to you a step by step process on how to create a simple product programmatically in Magento 2. When we build some functionality related to the product, we may need to create a large number of products. But when we perform tasks from the admin panel and create the product from the admin panel, it takes longer than regular.
This is when the script can be helpful for creating a simple product quickly.
Steps to Create Simple Product Programmatically in Magento 2
Let’s create the script for that.
Step 1. Create simpleproduct.php file at your Magento’s root folder :
<?php use Magento\Framework\App\Bootstrap; require __DIR__ . '/app/bootstrap.php'; $params = $_SERVER; $bootstrap = Bootstrap::create(BP, $params); $objectManager = $bootstrap->getObjectManager(); $state = $objectManager->get('Magento\Framework\App\State'); $state->setAreaCode('frontend'); $product = $objectManager->create('Magento\Catalog\Model\Product'); try { $product->setName('Sample Product'); $product->setTypeId('simple'); $product->setAttributeSetId(4); $product->setSku('sample-product'); $product->setWebsiteIds([1]); $product->setVisibility(4); $product->setPrice([1]); $product->setImage('/sample/test.jpg'); $product->setSmallImage('/sample/test.jpg'); $product->setThumbnail('/sample/test.jpg'); $product->setStockData( [ 'use_config_manage_stock' => 0, 'manage_stock' => 1, 'min_sale_qty' => 1, 'max_sale_qty' => 2, 'is_in_stock' => 1, 'qty' => 100 ] ); $product->save(); /** * For Add Custom Options */ $options = [ [ "sort_order" => 1, "title" => "Custom Option 1", "price_type" => "fixed", "price" => "10", "type" => "field", "is_require" => 0 ], [ "sort_order" => 2, "title" => "Custom Option 2", "price_type" => "fixed", "price" => "20", "type" => "field", "is_require" => 0 ] ]; foreach ($options as $customOptions) { $product->setHasOptions(1); $product->getResource()->save($product); $option = $objectManager->create('\Magento\Catalog\Model\Product\Option') ->setProductId($product->getId()) ->setStoreId($product->getStoreId()) ->addData($customOptions); $option->save(); $product->addOption($option); } } catch (Exception $ex) { echo $e->getMessage(); }
The static details can be set based on the requirements. If you are looking for creating multiple products programmatically by the script at that time, you can use this script and customize code for multiple products create.
In this script, an option array is used to add custom options in simple products. The code after the custom option comment line can be removed if you don’t want to add a custom option.
Step 2. Now, execute this file at frontend side.
{baseUrl}/simpleproduct.php
Hope this article helped you easily understand how to create a simple product programmatically in Magento 2. If in case, there is anything that is missed or you need to add some information, feel free to leave a comment in this blog, Our Magento experts will get back as soon as possible.