Magento 2 How to Create Simple Product Programmatically.

Hello Guys!

In this blog, we create simple products programmatically using Magento 2 root scripts.

In e-commerce, the product is an essential part. Magento 2 has 6 types of products.

Magento 2 has the following type of product :

  1. Simple Product
  2. Configurable Product
  3. Group Product
  4. Bundle Product
  5. Virtual Product
  6. Downloadable product

So we share some code to create simple products easily in Magento 2.

Step 1: add simple-product.php in Magento 2 root

<?php
use Magento\Framework\AppInterface;

try {
    require_once __DIR__ . '/app/bootstrap.php';

} catch (\Exception $e) {
    echo 'Autoload error: ' . $e->getMessage();
    exit(1);
}
try{
    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);

    $objectManager = $bootstrap->getObjectManager();

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

    $product = $objectManager->create('\Magento\Catalog\Model\Product');
    $product->setSku('sku-test'); // Product sku
    $product->setName('Test Sample Product'); // Product Name
    $product->setAttributeSetId(4); // here set Attribute set id
    $product->setStatus(1); // Here set Status on product enabled/ disabled 1/0
    $product->setWeight(10); 
    $product->setVisibility(4); // Set visibilty of product (catalog / search / catalog, search / Not visible individually)
    $product->setTaxClassId(0); // Set Tax class id
    $product->setTypeId('simple'); // Here set type of product (simple/virtual/downloadable/configurable)
    $product->setPrice(100); 
    $product->setStockData(
        array(
            'use_config_manage_stock' => 0,
            'manage_stock' => 1,
            'is_in_stock' => 1,
            'qty' => 999999999
        )
    );
    $product->save();

    // Adding Image to product
    $imagePath = "simple-image.png"; // path of the image
    $product->addImageToMediaGallery($imagePath, array('image', 'small_image', 'thumbnail'), false, false);
    $product->save();
}
catch(\Exception $e){
    print_r($e->getMessage());
}




Happy Coding 😊

How useful was this post?

Click on a star to rate it!

Average rating 4.7 / 5. Vote count: 12

No votes so far! Be the first to rate this post.

Leave a Reply

Your email address will not be published. Required fields are marked *