Magento Tutorials

How to Create Simple Product Programmatically in Magento 2

Hello Magento Folks,

In this tutorial blog, I will illustrate How to Create Simple Product Programmatically in Magento 2. When you work with Magento then you might be familiar with all the product types. If you are not familiar then check out my previous article where I have explained all the types of products in Magento 2

Basically while working in Magento 2 you will come across the types of products. And if you are in requirement of a large number of products then it will take much time if you go to create each and every product via the admin panel. Therefore for this kind of requirement, Magento allows creating products programmatically. To perform this task then follow the below instructed steps to Create Simple Product Programmatically in Magento 2.

Mainly we can create 6 types of products Programmatically in Magento 2:

  • Simple Product
  • Configurable Product
  • Grouped Product
  • Virtual Product
  • Bundle Product
  • Downloadable Product

Steps to Create Simple Product Programmatically in Magento 2:

Step 1 : Firstly, create a simple_product.php file in the Magento root directory and add the below given code.

<?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');

$sku = 'your_sku';  // set your sku

$product->setSku($sku);

$product->setName('Simple Product Name'); // set your Product Name of Product

$product->setAttributeSetId(4); // set attribute id

$product->setStatus(1); // status enabled/disabled 1/0

$product->setWeight(1); // set weight of product

$product->setVisibility(4); // visibility of product (Not Visible Individually (1) / Catalog (2)/ Search (3)/ Catalog, Search(4))

$product->setWebsiteIds(array(1));

$product->setTaxClassId(0); // Tax class ID

$product->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)

$product->setPrice(100); // set price of product

$product->setStockData(

      array(

      'use_config_manage_stock' => 0,

      'manage_stock' => 1,

      'is_in_stock' => 1,

      'qty' => 100
      )
    );

$product->save();

$categoryIds = array('2','3'); // assign your product to category using Category Id

    $category = $objectManager->get('Magento\Catalog\Api\CategoryLinkManagementInterface');

$category->assignProductToCategories($sku, $categoryIds);

echo "$sku Product Created Successfully ";

}

catch(\Exception $e){

print_r($e->getMessage());

}

Step 2: After the above step you will need to run the below-given URL to create a simple product.

https://yourdomain.com/simple_product.php

Wrap Up:

Hopefully, with the above code all are able to Create Simple Product Programmatically in your Magento 2. As always, don’t forget to clear cache and reindex if you are unable to view the output on the frontend of your store. In case you require some help during the implementation of the above illustration then let me know in the comment section below I will help you there. 

Share the article with your friends and family

Happy Reading!

Click to rate this post!
[Total: 10 Average: 4.2]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

View Comments

Recent Posts

Five Essential Payroll Compliance Tips for eCommerce Startups

Are you setting up a payroll system for your eCommerce startup? Ensuring compliance with myriad…

10 hours ago

Optimizing Laravel Blade: Unlocking Advanced Fetcher Techniques

In the expansive universe of Laravel development, Blade serves as the stellar templating engine, propelling…

12 hours ago

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

2 days ago

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

5 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

1 week ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

1 week ago