Programmatically create a simple product in magento 2

I'd like to create simple product programmatically in magento 2. Is there any way to create ?


Here, I found the solutions to create a product programmatically via custom php file i.e. test.php .

use Magento\Framework\App\Bootstrap;
$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();

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

$_product = $objectManager->create('Magento\Catalog\Model\Product');
$_product->setName('Test Product');
        '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' => 100 //qty


First, in your constructor you'll want to include three classes for dependency injection: Magento\Catalog\Api\Data\ProductInterfaceFactory, Magento\Catalog\Api\ProductRepositoryInterface and Magento\CatalogInventory\Api\StockRegistryInterface. The first is generated, so don't get too concerned if it shows up as not existing in your IDE.

public function __construct(\Magento\Catalog\Api\Data\ProductInterfaceFactory $productFactory, \Magento\Catalog\Api\ProductRepositoryInterface $productRepository, \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry)
    $this->productFactory = $productFactory;
    $this->productRepository = $productRepository;
    $this->stockRegistry = $stockRegistry;

From there, where you want to create the product, you'll need to use the Factory to create it and set the data, and the repository to save it:

/** @var \Magento\Catalog\Api\Data\ProductInterface $product */
$product = $this->productFactory->create();
$product->setName('Sample Item');
$product->setAttributeSetId(4); // Default attribute set for products
// If desired, you can set a tax class like so:
$product->setCustomAttribute('tax_class_id', $taxClassId);

$product = $this->productRepository->save($product); // This is important - the version provided and the version returned will be different objects

You'll likely then want to add some stock for it, which you can do like this:

$stockItem = $this->stockRegistry->getStockItemBySku($product->getSku());
$this->stockRegistry->updateStockItemBySku($product->getSku(), $stockItem);

If you're running this in a script (including setup/upgrade scripts), then you're also going to need to emulate the area as this sort of thing requires sessions for some crazy reason.

To do that, pull in \Magento\Framework\App\State through the constructor, and then utilize this code:

    function () { 
        /* all code here */ 
use \Magento\Framework\App\Bootstrap;

// add bootstrap
$bootstraps = Bootstrap::create(BP, $_SERVER);
$object_Manager = $bootstraps->getObjectManager();

$app_state = $object_Manager->get('\Magento\Framework\App\State');

// get date 
$today_date = date("m/d/Y");
$added_date = date('m/d/Y',strtotime("+17 day"));

$set_product = $object_Manager->create('\Magento\Catalog\Model\Product');

    // time of product creation
    $set_product->setName('Test Sample Products'); 
    // add Name of Product
    // add sku hear
    // add weight of product
    $category_id= array(4,5);
    // add your catagory id
    // Product Category
    // type of tax class 
    // (0 - none, 1 - default, 2 - taxable, 4 - shipping)
    // catalog and search visibility
    // manufacturer id
    // product set as new from
    // add image path hear
    // add small image path hear
    // add Thumbnail image path hear
    // product set as new to
    // country of manufacture (2-letter country code)
    $set_product->setPrice(100.99) ;
    // price in form 100.99
    // price in form 88.33
    // special price in form 99.85
    // special price from (MM-DD-YYYY)
    // special price to (MM-DD-YYYY)
    // enable MAP
    // display actual price 
    // (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
    // Manufacturer's Suggested Retail Price
    $set_product->setMetaTitle('test meta title 2');
    $set_product->setMetaKeyword('test meta keyword 2');
    $set_product->setMetaDescription('test meta description 2');
    $set_product->setDescription('This is a long description');
    $set_product->setShortDescription('This is a short description');
        'use_config_manage_stock' => 0, 
        // checkbox for 'Use config settings' 
        'manage_stock' => 1, // manage stock
        'min_sale_qty' => 1, // Shopping Cart Minimum Qty Allowed 
        'max_sale_qty' => 2, // Shopping Cart Maximum Qty Allowed
        'is_in_stock' => 1, // Stock Availability of product
        'qty' => 100 // qty of product

    // get id of product
    $get_product_id = $set_product->getId();
    echo "Upload simple product id :: ".$get_product_id."\n";
catch(Exception $exception)
    // errro in exception/code

code reference ::

Similar questions

Simple Configurable Products - add text before price of simple product
I am using the Simple Configurable Products extension. Right now there is text before a configurable product price that reads "starts at" How can I add text to precede the price of a simple product? Can I limit that text to simple products in certain categories only?
Find all Simple Products without category. Assign Cat to simple Product who is child of configurable
We have many Simple Products without an assigned category. Now i need to find all Simple Products by scripts which donĀ“t have a category. My idea was: Find all configurable products who have simple products. Read the categoryid of the configurable and assign it to the childs simple products. How can I get all configurables with childs? How can I as...
Magento 2 - Set simple product Color when creating product programmatically
Can any one help me? When I create simple product in GUI I can set color value by dropdown menu. My question is: How to assign color value programmatically, when I create simple product? I have spend whole day searching a way do to it.
Unlink simple product variant from configurable product programmatically in magento 2
I want to unlink some (not all) simple products from configurable product. I don't want to delete simple products, I just want to unlink from the main configurable product programmatically.
How can I convert simple product to bundle product programmatically
I have a system which has a set of products of three "types": I need to: I know already about this extension but seems be capable of only converting simple -> bundle, while I also need grouped -> bundle conversion. UPDATE 2: Since it is not possible to change pro...
Programmatically add simple product for configuration product?
In magento 2 I had created 3 product via my code. Product type is configurable, simple, simple. so now don't know set two simple product into configuration product. thank for help!

Also ask

We use cookies to deliver the best possible experience on our website. By continuing to use this site, accepting or closing this box, you consent to our use of cookies. To learn more, visit our privacy policy.